Cli.cpp 14.1 KB
Newer Older
Nicolas Follet's avatar
Nicolas Follet committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*
 * Cli.cpp
 * Copyright (C) 2017  Belledonne Communications, Grenoble, France
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *  Created on: June 6, 2017
 *      Author: Nicolas Follet
 */

#include "../../components/core/CoreManager.hpp"
24
#include "../../utils/Utils.hpp"
Nicolas Follet's avatar
Nicolas Follet committed
25 26 27 28 29 30 31 32 33 34
#include "../App.hpp"

#include "Cli.hpp"

using namespace std;

// =============================================================================
// API.
// =============================================================================

35
static void cliShow (QHash<QString, QString> &) {
Nicolas Follet's avatar
Nicolas Follet committed
36 37 38 39
  App *app = App::getInstance();
  app->smartShowWindow(app->getMainWindow());
}

40 41 42 43 44 45
static void cliCall (QHash<QString, QString> &args) {
  CoreManager::getInstance()->getCallsListModel()->launchAudioCall(args["sip-address"]);
}

static void cliJoinConference (QHash<QString, QString> &args) {
  const QString sipAddress = args.take("sip-address");
Ronan's avatar
Ronan committed
46 47 48 49 50 51 52 53 54 55

  CoreManager *coreManager = CoreManager::getInstance();
  const shared_ptr<linphone::Core> core = coreManager->getCore();

  {
    shared_ptr<linphone::Address> address = core->getPrimaryContactParsed();
    address->setDisplayName(::Utils::appStringToCoreString(args.take("display-name")));
    core->setPrimaryContact(address->asString());
  }

56
  args["method"] = QStringLiteral("join-conference");
Ronan's avatar
Ronan committed
57
  coreManager->getCallsListModel()->launchAudioCall(sipAddress, args);
58 59
}

60 61
static void cliJoinConferenceAs (QHash<QString, QString> &args) {
  const QString fromSipAddress = args.take("guest-sip-address");
Ronan's avatar
Ronan committed
62 63
  const QString toSipAddress = args.take("sip-address");
  CoreManager *coreManager = CoreManager::getInstance();
64
  shared_ptr<linphone::ProxyConfig> proxyConfig = coreManager->getCore()->getDefaultProxyConfig();
Ronan's avatar
Ronan committed
65

66 67 68 69 70 71 72
  if (!proxyConfig) {
    qWarning() << QStringLiteral("You have no proxy config.");
    return;
  }

  const shared_ptr<const linphone::Address> currentSipAddress = proxyConfig->getIdentityAddress();
  const shared_ptr<const linphone::Address> askedSipAddress = linphone::Factory::get()->createAddress(
Ronan's avatar
Ronan committed
73 74
      ::Utils::appStringToCoreString(fromSipAddress)
    );
75 76
  if (!currentSipAddress->weakEqual(askedSipAddress)) {
    qWarning() << QStringLiteral("Guest sip address `%1` doesn't match with default proxy config.")
Ronan's avatar
Ronan committed
77
      .arg(fromSipAddress);
78
    return;
79
  }
Ronan's avatar
Ronan committed
80

81
  args["method"] = QStringLiteral("join-conference");
Ronan's avatar
Ronan committed
82
  coreManager->getCallsListModel()->launchAudioCall(toSipAddress, args);
83 84
}

85 86 87 88 89
static void cliInitiateConference (QHash<QString, QString> &args) {
  shared_ptr<linphone::Core> core = CoreManager::getInstance()->getCore();

  // Check identity.
  {
Ronan's avatar
Ronan committed
90
    shared_ptr<linphone::Address> address = core->interpretUrl(::Utils::appStringToCoreString(args["sip-address"]));
91
    if (!address || address->getUsername().empty()) {
92 93 94 95
      qWarning() << QStringLiteral("Unable to parse invalid sip address.");
      return;
    }

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    address->clean();

    const string sipAddress = address->asString();
    const string identity = core->getIdentity();
    if (sipAddress != identity) {
      qWarning() << QStringLiteral("Received different sip address from identity : `%1 != %2`.")
        .arg(::Utils::coreStringToAppString(identity))
        .arg(::Utils::coreStringToAppString(sipAddress));
      return;
    }
  }

  shared_ptr<linphone::Conference> conference = core->getConference();
  const QString id = args["conference-id"];

  if (conference) {
    if (conference->getId() == ::Utils::appStringToCoreString(id)) {
      qInfo() << QStringLiteral("Conference `%1` already exists.").arg(id);
      // TODO: Set the view to the "waiting call view".
      return;
    }

    qInfo() << QStringLiteral("Remove existing conference with id: `%1`.")
      .arg(::Utils::coreStringToAppString(conference->getId()));
    core->terminateConference();
  }

  qInfo() << QStringLiteral("Create conference with id: `%1`.").arg(id);
  conference = core->createConferenceWithParams(core->createConferenceParams());
  conference->setId(::Utils::appStringToCoreString(id));

  if (core->enterConference() == -1) {
    qWarning() << QStringLiteral("Unable to join created conference: `%1`.").arg(id);
    return;
  }
131 132
  App *app = App::getInstance();
  app->smartShowWindow(app->getCallsWindow());
133
  // TODO: Set the view to the "waiting call view".
Nicolas Follet's avatar
Nicolas Follet committed
134 135
}

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
// =============================================================================
// Helpers.
// =============================================================================

static QString splitWord (QString word, int &curPos, const int lineLength, const QString &padding) {
  QString out;
  out += word.mid(0, lineLength - curPos) + "\n" + padding;
  curPos = padding.length();
  word = word.mid(lineLength - curPos);
  while (word.length() > lineLength - curPos) {
    out += word.mid(0, lineLength - curPos);
    word = word.mid(lineLength - curPos);
    out += "\n" + padding;
  }
  out += word;
  curPos = word.length() + padding.length();
  return out;
}

static QString indentedWord (QString word, int &curPos, const int lineLength, const QString &padding) {
  QString out;
  if (curPos + word.length() > lineLength) {
    if (padding.length() + word.length() > lineLength) {
      out += splitWord(word, curPos, lineLength, padding);
    } else {
      out += QStringLiteral("\n");
      out += padding + word;
      curPos = padding.length();
    }
  } else {
    out += word;
    curPos += word.length();
  }
  return out;
}

static string multilineIndent (const QString &str, int indentationNumber = 0) {
  static const int lineLength(80);
  static const QRegExp spaceRegexp("(\\s)");
  const QString padding(indentationNumber * 2, ' ');

  QString out = padding;

  int indentedTextCurPos = padding.length();

  int spacePos = 0;
  int wordPos = spacePos;
  QString word;

  while ((spacePos = spaceRegexp.indexIn(str, spacePos)) != -1) {
    word = str.mid(wordPos, spacePos - wordPos);
    out += indentedWord(word, indentedTextCurPos, lineLength, padding);
    switch (str[spacePos].unicode()) {
      case '\n':
        out += "\n" + padding;
        indentedTextCurPos = padding.length();
        break;
      case '\t': // TAB as space.
      case ' ':
        if (indentedTextCurPos == lineLength) {
          out += "\n" + padding;
          indentedTextCurPos = padding.length();
        } else {
          out += " ";
          indentedTextCurPos += 1;
        }
        break;

      default:
        break;
    }
    spacePos += 1;
    wordPos = spacePos;
  }
  word = str.mid(wordPos);
  out += indentedWord(word, indentedTextCurPos, lineLength, padding);
  out += "\n";

  return ::Utils::appStringToCoreString(out);
}

Nicolas Follet's avatar
Nicolas Follet committed
217 218
// =============================================================================

219 220
Cli::Command::Command (
  const QString &functionName,
221
  const char *functionDescription,
222 223 224
  Cli::Function function,
  const QHash<QString, Cli::Argument> &argsScheme
) :
Nicolas Follet's avatar
Nicolas Follet committed
225
  mFunctionName(functionName),
226
  mFunctionDescription(functionDescription),
Nicolas Follet's avatar
Nicolas Follet committed
227 228 229
  mFunction(function),
  mArgsScheme(argsScheme) {}

230 231 232 233 234 235 236 237 238 239 240 241
void Cli::Command::execute (QHash<QString, QString> &args) const {
  // Check arguments validity.
  for (const auto &argName : args.keys()) {
    if (!mArgsScheme.contains(argName)) {
      qWarning() << QStringLiteral("Command with invalid argument: `%1 (%2)`.")
        .arg(mFunctionName).arg(argName);

      return;
    }
  }

  // Check missing arguments.
Nicolas Follet's avatar
Nicolas Follet committed
242
  for (const auto &argName : mArgsScheme.keys()) {
243
    if (!mArgsScheme[argName].isOptional && (!args.contains(argName) || args[argName].isEmpty())) {
Nicolas Follet's avatar
Nicolas Follet committed
244 245 246 247 248 249
      qWarning() << QStringLiteral("Missing argument for command: `%1 (%2)`.")
        .arg(mFunctionName).arg(argName);
      return;
    }
  }

250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
  // Execute!
  CoreManager *coreManager = CoreManager::getInstance();

  if (coreManager->started())
    (*mFunction)(args);
  else {
    Function f = mFunction;
    ::Utils::connectOnce(coreManager->getHandlers().get(), &CoreHandlers::coreStarted, coreManager, [f, args] {
      QHash<QString, QString> fuckConst = args;
      (*f)(fuckConst);
    });
  }
}

void Cli::Command::executeUri (const shared_ptr<linphone::Address> &address) const {
  QHash<QString, QString> args;
266
  // TODO: check if there is too much headers.
267 268
  for (const auto &argName : mArgsScheme.keys()) {
    const string header = address->getHeader(::Utils::appStringToCoreString(argName));
269
    args[argName] = QByteArray::fromBase64(QByteArray(header.c_str(), static_cast<int>(header.length())));
270
  }
271
  address->clean();
272
  args["sip-address"] = ::Utils::coreStringToAppString(address->asStringUriOnly());
273
  execute(args);
Nicolas Follet's avatar
Nicolas Follet committed
274 275
}

276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
QString Cli::Command::getFunctionSyntax () const {
  QString functionSyntax;
  functionSyntax += QStringLiteral("\"");
  functionSyntax += mFunctionName;
  for (auto &argName : mArgsScheme.keys()){
    functionSyntax += QStringLiteral(" ");
    functionSyntax += mArgsScheme[argName].isOptional ? QStringLiteral("[") : QStringLiteral("");
    functionSyntax += argName;
    functionSyntax += QStringLiteral("=<");
    switch (mArgsScheme[argName].type) {
      case STRING :
        functionSyntax += QStringLiteral("str");
        break;
      default:
        functionSyntax += QStringLiteral("value");
        break;
    }
    functionSyntax += QString(">");
    functionSyntax += mArgsScheme[argName].isOptional ? QStringLiteral("]") : QStringLiteral("");
  }
  functionSyntax += QStringLiteral("\"");
  return functionSyntax;
}

Nicolas Follet's avatar
Nicolas Follet committed
300 301
// =============================================================================

302 303
// FIXME: Do not accept args without value like: cmd toto.
// In the future `toto` could be a boolean argument.
304
QRegExp Cli::mRegExpArgs("(?:(?:([\\w-]+)\\s*)=\\s*(?:\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\"|([^\\s]+)\\s*))");
305
QRegExp Cli::mRegExpFunctionName("^\\s*([a-z-]+)\\s*");
Nicolas Follet's avatar
Nicolas Follet committed
306

307
QMap<QString, Cli::Command> Cli::mCommands = {
308 309
  createCommand("show", QT_TR_NOOP("showFunctionDescription"), ::cliShow),
  createCommand("call", QT_TR_NOOP("callFunctionDescription"), ::cliCall, {
310
    { "sip-address", {} }
311
  }),
312
  createCommand("initiate-conference", QT_TR_NOOP("initiateConferenceFunctionDescription"), ::cliInitiateConference, {
313
    { "sip-address", {} }, { "conference-id", {} }
314
  }),
315
  createCommand("join-conference", QT_TR_NOOP("joinConferenceFunctionDescription"), ::cliJoinConference, {
316
    { "sip-address", {} }, { "conference-id", {} }, { "display-name", {} }
317
  }),
318
  createCommand("join-conference-as", QT_TR_NOOP("joinConferenceAsFunctionDescription"), ::cliJoinConferenceAs, {
319
    { "sip-address", {} }, { "conference-id", {} }, { "guest-sip-address", {} }
320 321
  })
};
Nicolas Follet's avatar
Nicolas Follet committed
322 323 324

// -----------------------------------------------------------------------------

325
void Cli::executeCommand (const QString &command, CommandFormat *format) {
326 327 328 329 330 331 332 333 334 335 336 337
  shared_ptr<linphone::Address> address = linphone::Factory::get()->createAddress(
      ::Utils::appStringToCoreString(command)
    );

  // Execute cli command.
  if (!address) {
    const QString &functionName = parseFunctionName(command);
    if (!functionName.isEmpty()) {
      QHash<QString, QString> args = parseArgs(command);
      mCommands[functionName].execute(args);
    }

338 339 340
    if (format)
      *format = CliFormat;

Nicolas Follet's avatar
Nicolas Follet committed
341
    return;
342
  }
Nicolas Follet's avatar
Nicolas Follet committed
343

344 345 346
  if (format)
    *format = UriFormat;

347
  // Execute uri command.
348 349
  qInfo() << QStringLiteral("Execute uri command: `%1`.").arg(command);

350
  string scheme = address->getScheme();
351
  if (scheme != "sip" && scheme != "sip-linphone") {
352
    qWarning() << QStringLiteral("Not a valid uri: `%1`.").arg(command);
Nicolas Follet's avatar
Nicolas Follet committed
353
    return;
354 355 356 357 358
  }

  const QString functionName = ::Utils::coreStringToAppString(address->getHeader("method")).isEmpty()
    ? QStringLiteral("call")
    : ::Utils::coreStringToAppString(address->getHeader("method"));
Nicolas Follet's avatar
Nicolas Follet committed
359

360 361 362 363 364 365
  if (!functionName.isEmpty() && !mCommands.contains(functionName)) {
    qWarning() << QStringLiteral("This command doesn't exist: `%1`.").arg(functionName);
    return;
  }

  mCommands[functionName].executeUri(address);
Nicolas Follet's avatar
Nicolas Follet committed
366 367
}

368 369 370 371 372 373 374 375 376 377 378
void Cli::showHelp () {
  cout << multilineIndent(tr("linphoneCliDescription"), 0) <<
    endl <<
    "Usage: " <<
    endl <<
    multilineIndent(tr("uriCommandLineSyntax"), 0) <<
    multilineIndent(tr("cliCommandLineSyntax"), 0) <<
    endl <<
    multilineIndent(tr("commandsName")) << endl;

  for (const auto &method : mCommands.keys())
379
    cout << multilineIndent(mCommands[method].getFunctionSyntax(), 1) <<
380 381
      multilineIndent(tr(mCommands[method].getFunctionDescription()), 2) <<
      endl;
382 383
}

384
// -----------------------------------------------------------------------------
385

386 387 388 389 390 391
pair<QString, Cli::Command> Cli::createCommand (
  const QString &functionName,
  const char *functionDescription,
  Function function,
  const QHash<QString, Argument> &argsScheme
) {
392
  return { functionName, Cli::Command(functionName, functionDescription, function, argsScheme) };
393 394
}

Nicolas Follet's avatar
Nicolas Follet committed
395 396
// -----------------------------------------------------------------------------

397
QString Cli::parseFunctionName (const QString &command) {
Nicolas Follet's avatar
Nicolas Follet committed
398
  mRegExpFunctionName.indexIn(command);
Ronan's avatar
Ronan committed
399
  if (mRegExpFunctionName.pos(1) == -1) {
Nicolas Follet's avatar
Nicolas Follet committed
400
    qWarning() << QStringLiteral("Unable to parse function name of command: `%1`.").arg(command);
401
    return QString("");
Nicolas Follet's avatar
Nicolas Follet committed
402 403
  }

Ronan's avatar
Ronan committed
404 405
  const QStringList texts = mRegExpFunctionName.capturedTexts();

Nicolas Follet's avatar
Nicolas Follet committed
406 407 408
  const QString functionName = texts[1];
  if (!mCommands.contains(functionName)) {
    qWarning() << QStringLiteral("This command doesn't exist: `%1`.").arg(functionName);
409
    return QString("");
Nicolas Follet's avatar
Nicolas Follet committed
410 411 412 413 414
  }

  return functionName;
}

415
QHash<QString, QString> Cli::parseArgs (const QString &command) {
Nicolas Follet's avatar
Nicolas Follet committed
416 417 418 419 420 421 422 423 424 425
  QHash<QString, QString> args;
  int pos = 0;

  while ((pos = mRegExpArgs.indexIn(command, pos)) != -1) {
    pos += mRegExpArgs.matchedLength();
    args[mRegExpArgs.cap(1)] = (mRegExpArgs.cap(2).isEmpty() ? mRegExpArgs.cap(3) : mRegExpArgs.cap(2));
  }

  return args;
}