| 1 | // For license of this file, see <project-root-folder>/LICENSE.md. |
| 2 | |
| 3 | #include "miscellaneous/textfactory.h" |
| 4 | |
| 5 | #include "3rd-party/boolinq/boolinq.h" |
| 6 | #include "3rd-party/sc/simplecrypt.h" |
| 7 | #include "definitions/definitions.h" |
| 8 | #include "exceptions/applicationexception.h" |
| 9 | #include "miscellaneous/application.h" |
| 10 | #include "miscellaneous/iofactory.h" |
| 11 | #include "miscellaneous/settings.h" |
| 12 | |
| 13 | #include <QDir> |
| 14 | #include <QLocale> |
| 15 | #include <QRandomGenerator64> |
| 16 | #include <QString> |
| 17 | #include <QStringList> |
| 18 | #include <QTextDocument> |
| 19 | |
| 20 | quint64 TextFactory::s_encryptionKey = 0x0; |
| 21 | |
| 22 | TextFactory::TextFactory() = default; |
| 23 | |
| 24 | QString TextFactory::extractUsernameFromEmail(const QString& email_address) { |
| 25 | const int zav = email_address.indexOf('@'); |
| 26 | |
| 27 | if (zav >= 0) { |
| 28 | return email_address.mid(0, zav); |
| 29 | } |
| 30 | else { |
| 31 | return email_address; |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | QColor TextFactory::generateColorFromText(const QString& text) { |
| 36 | quint32 color = 0; |
| 37 | |
| 38 | for (const QChar chr : text) { |
| 39 | color += chr.unicode(); |
| 40 | } |
| 41 | |
| 42 | // NOTE: https://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically |
| 43 | int hue = color % 360; |
| 44 | |
| 45 | return QColor::fromHsv(hue, 200, 240); |
| 46 | } |
| 47 | |
| 48 | QColor TextFactory::generateRandomColor() { |
| 49 | int hue = QRandomGenerator::global()->generate() % 360; |
| 50 | auto clr = QColor::fromHsv(hue, 200, 240); |
| 51 | |
| 52 | return clr; |
| 53 | } |
| 54 | |
| 55 | int TextFactory::stringHeight(const QString& string, const QFontMetrics& metrics) { |
| 56 | const int count_lines = string.split(QL1C('\n')).size(); |
| 57 | |
| 58 | return metrics.height() * count_lines; |
| 59 | } |
| 60 | |
| 61 | int TextFactory::stringWidth(const QString& string, const QFontMetrics& metrics) { |
| 62 | const QStringList lines = string.split(QL1C('\n')); |
| 63 | int width = 0; |
| 64 | |
| 65 | for (const QString& line : lines) { |
| 66 | int line_width = metrics.horizontalAdvance(line); |
| 67 | |
| 68 | if (line_width > width) { |
| 69 | width = line_width; |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | return width; |
| 74 | } |
| 75 | |
| 76 | bool TextFactory::couldBeHtml(const QString& string) { |
| 77 | const QString sstring = string.simplified(); |
| 78 | |
| 79 | static QRegularExpression |
| 80 | tag_exp(QSL("^<(" |
| 81 | "a|abbr|address|area|article|aside|audio|" |
| 82 | "b|base|bdi|bdo|blockquote|body|br|button|" |
| 83 | "canvas|caption|cite|code|col|colgroup|" |
| 84 | "data|datalist|dd|del|details|dfn|dialog|div|dl|dt|" |
| 85 | "em|embed|" |
| 86 | "fieldset|figcaption|figure|footer|form|" |
| 87 | "h1|h2|h3|h4|h5|h6|head|header|hgroup|hr|html|" |
| 88 | "i|iframe|img|input|ins|" |
| 89 | "kbd|" |
| 90 | "label|legend|li|link|" |
| 91 | "main|map|mark|menu|meta|meter|" |
| 92 | "nav|noscript|" |
| 93 | "object|ol|optgroup|option|output|" |
| 94 | "p|picture|pre|progress|" |
| 95 | "q|" |
| 96 | "rp|rt|ruby|" |
| 97 | "s|samp|script|search|section|select|slot|small|source|span|strong|style|sub|summary|sup|" |
| 98 | "table|tbody|td|template|textarea|tfoot|th|thead|time|title|tr|track|" |
| 99 | "u|ul|" |
| 100 | "var|video|" |
| 101 | "wbr|" |
| 102 | "!" |
| 103 | ")")); |
| 104 | |
| 105 | return tag_exp.match(sstring).hasMatch() || Qt::mightBeRichText(sstring); |
| 106 | } |
| 107 | |
| 108 | QDateTime TextFactory::parseDateTime(const QString& date_time, QString* used_dt_format) { |
| 109 | QString input_date = date_time.simplified() |
| 110 | .replace(QSL("GMT"), QSL("+0000")) |
| 111 | .replace(QSL("UTC"), QSL("+0000")) |
| 112 | .replace(QSL("UT"), QSL("+0000")) |
| 113 | .replace(QSL("EDT"), QSL("-0400")) |
| 114 | .replace(QSL("EST"), QSL("-0500")) |
| 115 | .replace(QSL("PDT"), QSL("-0700")) |
| 116 | .replace(QSL("PST"), QSL("-0800")) |
| 117 | .replace(QRegularExpression(QSL("\\.(\\d{3})\\d{3}")), QSL(".\\1")); |
| 118 | |
| 119 | if (input_date.isEmpty()) { |
| 120 | return QDateTime(); |
| 121 | } |
| 122 | |
| 123 | QLocale locale(QLocale::Language::C); |
| 124 | QDateTime dt; |
| 125 | QStringList date_patterns = dateTimePatterns(true); |
| 126 | |
| 127 | if (used_dt_format != nullptr && !used_dt_format->isEmpty()) { |
| 128 | date_patterns.prepend(*used_dt_format); |
| 129 | } |
| 130 | |
| 131 | // QDateTime dt1 = locale.toDateTime("GMT", "t"); |
| 132 | // QString dt2 = dt1.toString(); |
| 133 | |
| 134 | for (const QString& pattern : std::as_const(date_patterns)) { |
| 135 | #if QT_VERSION >= 0x060700 // Qt >= 6.7.0 |
| 136 | dt = locale.toDateTime(input_date, pattern, 2000); |
| 137 | #else |
| 138 | dt = locale.toDateTime(input_date, pattern); |
| 139 | #endif |
| 140 | |
| 141 | if (dt.isValid()) { |
| 142 | // Make sure that this date/time is considered UTC. |
| 143 | dt = dt.toUTC(); |
| 144 | |
| 145 | if (used_dt_format != nullptr) { |
| 146 | used_dt_format->clear(); |
| 147 | used_dt_format->append(pattern); |
| 148 | } |
| 149 | |
| 150 | return dt; |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | qCriticalNN << LOGSEC_CORE << "Date/time string NOT recognized:" << QUOTE_W_SPACE_DOT(input_date); |
| 155 | return QDateTime(); |
| 156 | } |
| 157 | |
| 158 | QDateTime TextFactory::parseDateTime(qint64 milis_from_epoch) { |
| 159 | return QDateTime::fromMSecsSinceEpoch(milis_from_epoch, Qt::TimeSpec::UTC); |
| 160 | } |
| 161 | |
| 162 | QStringList TextFactory::dateTimePatterns(bool with_tzs) { |
| 163 | QStringList pat; |
| 164 | |
| 165 | pat << QSL("yyyy-MM-ddTHH:mm:ss"); |
| 166 | pat << QSL("yyyy-MM-ddTHH:mm:ss.z"); |
| 167 | pat << QSL("yyyy-MM-ddTHH:mm:ss.zzz"); |
| 168 | pat << QSL("yyyy-MM-ddThh:mm:ss"); |
| 169 | pat << QSL("yyyy-MM-dd HH:mm:ss.z"); |
| 170 | |
| 171 | pat << QSL("yyyy-MM-ddThh:mm"); |
| 172 | |
| 173 | pat << QSL("yyyyMMddThhmmss"); |
| 174 | pat << QSL("yyyyMMdd"); |
| 175 | pat << QSL("yyyy"); |
| 176 | |
| 177 | pat << QSL("yyyy-MM-dd"); |
| 178 | pat << QSL("yyyy-MM"); |
| 179 | |
| 180 | pat << QSL("MMM dd yyyy hh:mm:ss"); |
| 181 | pat << QSL("MMM d yyyy hh:mm:ss"); |
| 182 | |
| 183 | pat << QSL("ddd, dd MMM yyyy HH:mm:ss"); |
| 184 | pat << QSL("ddd, dd MMM yyyy HH:mm"); |
| 185 | pat << QSL("ddd, dd MMM yy HH:mm:ss"); |
| 186 | pat << QSL("ddd, dd MMMM yyyy HH:mm:ss"); |
| 187 | pat << QSL("ddd, d MMM yyyy HH:mm:ss"); |
| 188 | |
| 189 | pat << QSL("ddd, MM/dd/yyyy - HH:mm"); |
| 190 | |
| 191 | pat << QSL("dd MMM yyyy hh:mm:ss"); |
| 192 | pat << QSL("dd MMM yyyy hh:mm"); |
| 193 | pat << QSL("dd MMM yyyy"); |
| 194 | |
| 195 | pat << QSL("d MMM yyyy HH:mm:ss"); |
| 196 | pat << QSL("d MMM yyyy HH:mm"); |
| 197 | |
| 198 | pat << QSL("dd-MM-yyyy - HH:mm"); |
| 199 | |
| 200 | pat << QSL("hh:mm:ss"); |
| 201 | pat << QSL("h:m:s"); |
| 202 | pat << QSL("h:mm"); |
| 203 | pat << QSL("H:mm"); |
| 204 | pat << QSL("h:m"); |
| 205 | pat << QSL("h.m"); |
| 206 | |
| 207 | if (with_tzs) { |
| 208 | for (int i = 0; i < pat.size(); i += 3) { |
| 209 | QString base_pattern = pat.value(i); |
| 210 | |
| 211 | pat.insert(i + 1, base_pattern + QSL("t")); |
| 212 | pat.insert(i + 2, base_pattern + QSL(" t")); |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | return pat; |
| 217 | } |
| 218 | |
| 219 | QString TextFactory::encrypt(const QString& text, quint64 key) { |
| 220 | return SimpleCrypt(key == 0 ? initializeSecretEncryptionKey() : key).encryptToString(text); |
| 221 | } |
| 222 | |
| 223 | QString TextFactory::decrypt(const QString& text, quint64 key) { |
| 224 | return SimpleCrypt(key == 0 ? initializeSecretEncryptionKey() : key).decryptToString(text); |
| 225 | } |
| 226 | |
| 227 | QString TextFactory::newline() { |
| 228 | #if defined(Q_OS_WIN) |
| 229 | return QSL("\r\n"); |
| 230 | #elif defined(Q_OS_MACOS) |
| 231 | return QSL("\r"); |
| 232 | #else |
| 233 | return QSL("\n"); |
| 234 | #endif |
| 235 | } |
| 236 | |
| 237 | QString TextFactory::capitalizeFirstLetter(const QString& sts) { |
| 238 | if (sts.isEmpty()) { |
| 239 | return sts; |
| 240 | } |
| 241 | else { |
| 242 | return sts[0].toUpper() + sts.mid(1); |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | enum class TokenState { |
| 247 | // We are not inside argument, we are between arguments. |
| 248 | Normal, |
| 249 | |
| 250 | // We have detected escape "\" character coming from double-quoted argument. |
| 251 | EscapedFromDoubleQuotes, |
| 252 | |
| 253 | // We have detected escape "\" character coming from spaced argument. |
| 254 | EscapedFromSpaced, |
| 255 | |
| 256 | // We are inside argument which was separated by spaces. |
| 257 | InsideArgSpaced, |
| 258 | |
| 259 | // We are inside argument. |
| 260 | InsideArgDoubleQuotes, |
| 261 | |
| 262 | // We are inside argument, do not evaluate anything, just take it all |
| 263 | // as arw text. |
| 264 | InsideArgSingleQuotes |
| 265 | }; |
| 266 | |
| 267 | QStringList TextFactory::tokenizeProcessArguments(const QString& command) { |
| 268 | // Each argument containing spaces must be enclosed with single '' or double "" quotes. |
| 269 | // Some characters must be escaped with \ to keep their textual values as |
| 270 | // long as double-quoted argument is used. |
| 271 | |
| 272 | if (command.isEmpty()) { |
| 273 | return {}; |
| 274 | } |
| 275 | |
| 276 | // We append space to end of command to make sure that |
| 277 | // ending space-separated argument is processed. |
| 278 | QString my_command = command + u' '; |
| 279 | |
| 280 | TokenState state = TokenState::Normal; |
| 281 | QStringList args; |
| 282 | QString arg; |
| 283 | |
| 284 | for (QChar chr : my_command) { |
| 285 | switch (state) { |
| 286 | case TokenState::Normal: { |
| 287 | switch (chr.unicode()) { |
| 288 | case u'"': |
| 289 | // We start double-quoted argument. |
| 290 | state = TokenState::InsideArgDoubleQuotes; |
| 291 | continue; |
| 292 | |
| 293 | case u'\'': |
| 294 | // We start single-quoted argument. |
| 295 | state = TokenState::InsideArgSingleQuotes; |
| 296 | continue; |
| 297 | |
| 298 | case u' ': |
| 299 | // Whitespace, just go on. |
| 300 | continue; |
| 301 | |
| 302 | default: |
| 303 | // We found some actual text which marks |
| 304 | // beginning of argument, we assume spaced argument. |
| 305 | arg.append(chr); |
| 306 | state = TokenState::InsideArgSpaced; |
| 307 | continue; |
| 308 | } |
| 309 | |
| 310 | break; |
| 311 | } |
| 312 | |
| 313 | case TokenState::EscapedFromDoubleQuotes: { |
| 314 | // Previous character was "\". |
| 315 | arg.append(chr); |
| 316 | state = TokenState::InsideArgDoubleQuotes; |
| 317 | break; |
| 318 | } |
| 319 | |
| 320 | case TokenState::EscapedFromSpaced: { |
| 321 | // Previous character was "\". |
| 322 | arg.append(chr); |
| 323 | state = TokenState::InsideArgSpaced; |
| 324 | break; |
| 325 | } |
| 326 | |
| 327 | case TokenState::InsideArgSpaced: { |
| 328 | switch (chr.unicode()) { |
| 329 | // NOTE: Probably disable escaping in spaced arguments to provide simpler UX? |
| 330 | /* |
| 331 | case u'\\': |
| 332 | // We found escaped! |
| 333 | state = TokenState::EscapedFromSpaced; |
| 334 | continue; |
| 335 | */ |
| 336 | |
| 337 | case u' ': |
| 338 | // We need to end this argument. |
| 339 | args.append(arg); |
| 340 | arg.clear(); |
| 341 | state = TokenState::Normal; |
| 342 | continue; |
| 343 | |
| 344 | default: |
| 345 | arg.append(chr); |
| 346 | break; |
| 347 | } |
| 348 | |
| 349 | break; |
| 350 | } |
| 351 | |
| 352 | case TokenState::InsideArgDoubleQuotes: { |
| 353 | switch (chr.unicode()) { |
| 354 | case u'\\': |
| 355 | // We found escaped! |
| 356 | state = TokenState::EscapedFromDoubleQuotes; |
| 357 | continue; |
| 358 | |
| 359 | case u'"': |
| 360 | // We need to end this argument. |
| 361 | args.append(arg); |
| 362 | arg.clear(); |
| 363 | state = TokenState::Normal; |
| 364 | continue; |
| 365 | |
| 366 | default: |
| 367 | arg.append(chr); |
| 368 | break; |
| 369 | } |
| 370 | |
| 371 | break; |
| 372 | } |
| 373 | |
| 374 | case TokenState::InsideArgSingleQuotes: { |
| 375 | switch (chr.unicode()) { |
| 376 | case u'\'': |
| 377 | // We need to end this argument. |
| 378 | args.append(arg); |
| 379 | arg.clear(); |
| 380 | state = TokenState::Normal; |
| 381 | continue; |
| 382 | |
| 383 | default: |
| 384 | arg.append(chr); |
| 385 | break; |
| 386 | } |
| 387 | |
| 388 | break; |
| 389 | } |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | switch (state) { |
| 394 | case TokenState::EscapedFromSpaced: |
| 395 | case TokenState::EscapedFromDoubleQuotes: |
| 396 | throw ApplicationException(QObject::tr("escape sequence not completed")); |
| 397 | break; |
| 398 | |
| 399 | case TokenState::InsideArgDoubleQuotes: |
| 400 | throw ApplicationException(QObject::tr("closing \" is missing")); |
| 401 | break; |
| 402 | |
| 403 | case TokenState::InsideArgSingleQuotes: |
| 404 | throw ApplicationException(QObject::tr("closing ' is missing")); |
| 405 | break; |
| 406 | |
| 407 | default: |
| 408 | break; |
| 409 | } |
| 410 | |
| 411 | return args; |
| 412 | } |
| 413 | |
| 414 | QString TextFactory::shorten(const QString& input, int text_length_limit) { |
| 415 | if (input.size() > text_length_limit) { |
| 416 | return input.left(text_length_limit - ELLIPSIS_LENGTH) + QString(ELLIPSIS_LENGTH, QL1C('.')); |
| 417 | } |
| 418 | else { |
| 419 | return input; |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | quint64 TextFactory::initializeSecretEncryptionKey() { |
| 424 | if (s_encryptionKey == 0x0) { |
| 425 | // Check if file with encryption key exists. |
| 426 | QString encryption_file_path = qApp->settings()->pathName() + QDir::separator() + ENCRYPTION_FILE_NAME; |
| 427 | |
| 428 | try { |
| 429 | s_encryptionKey = quint64(QString(IOFactory::readFile(encryption_file_path)).toULongLong()); |
| 430 | } |
| 431 | catch (ApplicationException&) { |
| 432 | // Well, key does not exist or is invalid, generate and save one. |
| 433 | s_encryptionKey = generateSecretEncryptionKey(); |
| 434 | |
| 435 | try { |
| 436 | IOFactory::writeFile(encryption_file_path, QString::number(s_encryptionKey).toLocal8Bit()); |
| 437 | } |
| 438 | catch (ApplicationException& ex) { |
| 439 | qCriticalNN << LOGSEC_CORE << "Failed to write newly generated encryption key to file, error" |
| 440 | << QUOTE_W_SPACE_DOT(ex.message()) |
| 441 | << " Now, your passwords won't be readable after you start this application again."; |
| 442 | } |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | return s_encryptionKey; |
| 447 | } |
| 448 | |
| 449 | quint64 TextFactory::generateSecretEncryptionKey() { |
| 450 | return QRandomGenerator64::global()->generate(); |
| 451 | } |