cinera.c 250 KB
Newer Older
1 2
#if 0
ctime -begin ${0%.*}.ctm
3 4
#gcc -g -fsanitize=address -Wall -std=c99 -pipe $0 -o ${0%.*} hmml.a -lcurl
gcc -O2 -Wall -std=c99 -pipe $0 -o ${0%.*} hmml.a -lcurl
5 6 7 8
ctime -end ${0%.*}.ctm
exit
#endif

Matt Mascarenhas's avatar
Matt Mascarenhas committed
9 10 11 12 13 14 15 16
typedef struct
{
    unsigned int Major, Minor, Patch;
} version;

version CINERA_APP_VERSION = {
    .Major = 0,
    .Minor = 5,
17
    .Patch = 36
Matt Mascarenhas's avatar
Matt Mascarenhas committed
18 19
};

20
// TODO(matt): Copy in the DB 3 stuff from cinera_working.c
21
#define CINERA_DB_VERSION 3
22

23
#define DEBUG 0
24
#define DEBUG_MEM 0
25

26
typedef unsigned int bool;
27 28 29 30

#define TRUE 1
#define FALSE 0

31 32 33
#include <stdarg.h> // NOTE(matt): varargs
#include <stdio.h>  // NOTE(matt): printf, sprintf, vsprintf, fprintf, perror
#include <stdlib.h> // NOTE(matt): calloc, malloc, free
34
#include "hmmlib.h"
35
#include <getopt.h> // NOTE(matt): getopts
36
//#include "config.h" // TODO(matt): Implement config.h
37
#include <curl/curl.h>
38 39
#include <time.h>
#include <sys/stat.h>
40 41
#include <sys/types.h>
#include <dirent.h>
42 43
#include <string.h> // NOTE(matt): strerror
#include <errno.h> //NOTE(matt): errno
44 45
#include <sys/inotify.h> // NOTE(matt): inotify
#include <unistd.h> // NOTE(matt): sleep()
46

47 48 49
#define Kilobytes(Bytes) Bytes << 10
#define Megabytes(Bytes) Bytes << 20

50 51 52 53 54 55 56 57 58
#define MAX_PROJECT_ID_LENGTH 31
#define MAX_PROJECT_NAME_LENGTH 63
#define MAX_BASE_URL_LENGTH 127
#define MAX_RELATIVE_PAGE_LOCATION_LENGTH 31
#define MAX_PLAYER_URL_PREFIX_LENGTH 15

#define MAX_BASE_FILENAME_LENGTH 31
#define MAX_TITLE_LENGTH 128 - (MAX_BASE_FILENAME_LENGTH + 1) - (int)sizeof(link_insertion_offsets) - (int)sizeof(unsigned short int) - 1 // NOTE(matt): We size this such that index_metadata is 128 bytes total

59 60 61
#define MAX_CUSTOM_SNIPPET_SHORT_LENGTH 255
#define MAX_CUSTOM_SNIPPET_LONG_LENGTH 1023

62 63
enum
{
64 65 66
    EDITION_SINGLE,
    EDITION_PROJECT,
    EDITION_NETWORK
67 68
} editions;

69 70 71 72 73 74 75 76 77 78 79 80 81
enum
{
    // NOTE(matt): https://tools.ietf.org/html/rfc5424#section-6.2.1
    LOG_EMERGENCY,
    LOG_ALERT,
    LOG_CRITICAL,
    LOG_ERROR,
    LOG_WARNING,
    LOG_NOTICE,
    LOG_INFORMATIONAL,
    LOG_DEBUG
} log_levels;

82 83
enum
{
84
    MODE_ONESHOT = 1 << 0,
85
    MODE_EXAMINE = 1 << 1,
86
    MODE_NOCACHE = 1 << 2,
87 88
} modes;

89 90 91 92 93 94 95 96 97
enum
{
    RC_ARENA_FULL,
    RC_ERROR_DIRECTORY,
    RC_ERROR_FATAL,
    RC_ERROR_FILE,
    RC_ERROR_HMML,
    RC_ERROR_MAX_REFS,
    RC_ERROR_MEMORY,
Matt Mascarenhas's avatar
Matt Mascarenhas committed
98
    RC_ERROR_PROJECT,
99
    RC_ERROR_QUOTE,
Matt Mascarenhas's avatar
Matt Mascarenhas committed
100
    RC_ERROR_SEEK,
101 102 103
    RC_FOUND,
    RC_UNFOUND,
    RC_INVALID_REFERENCE,
Matt Mascarenhas's avatar
Matt Mascarenhas committed
104
    RC_INVALID_TEMPLATE,
105 106 107 108 109 110 111 112 113 114 115 116 117
    RC_NOOP,
    RC_RIP,
    RC_SUCCESS
} returns;

typedef struct
{
    void *Location;
    void *Ptr;
    char *ID;
    int  Size;
} arena;

118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 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
typedef struct
{
    // Universal
    char  CacheDir[256];
    int   Edition;
    int   LogLevel;
    int   Mode;
    int   UpdateInterval;
    bool  ForceIntegration;

    // Advisedly universal, although could be per-project
    char *RootDir; // Absolute
    char *RootURL;
    char *CSSDir; // Relative to Root{Dir,URL}
    char *ImagesDir; // Relative to Root{Dir,URL}
    char *JSDir; // Relative to Root{Dir,URL}

    // Per Project
    char *ProjectID;
    char *Theme;
    char *DefaultMedium;

    // Per Project - Input
    char *ProjectDir; // Absolute
    char *TemplatesDir; // Absolute
    char *TemplateIndexLocation; // Relative to TemplatesDir ???
    char *TemplatePlayerLocation; // Relative to TemplatesDir ???

    // Per Project - Output
    char *BaseDir; // Absolute
    char *BaseURL;
    char *IndexLocation; // Relative to Base{Dir,URL}
    char *PlayerLocation; // Relative to Base{Dir,URL}
    char *PlayerURLPrefix; /* NOTE(matt): This will become a full blown customisable output URL.
                                    For now it simply replaces the ProjectID */
    // Single Edition - Input
    char SingleHMMLFilePath[256];

    // Single Edition - Output
    char *OutLocation;
    char *OutIntegratedLocation;
} config;

// NOTE(matt): Globals
config Config = {};
arena MemoryArena;
time_t LastQuoteFetch;
//

167 168 169 170
typedef struct
{
    char *Location;
    char *Ptr;
171
    char *ID;
172 173 174
    int  Size;
} buffer;

175 176 177 178
typedef struct
{
    buffer Buffer;
    FILE  *Handle;
179
    char   Path[256]; // NOTE(matt): Could this just be a char *?
180 181 182
    int    FileSize;
} file_buffer;

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 217 218 219 220 221 222 223 224 225 226
// TODO(matt): Increment CINERA_DB_VERSION!
typedef struct
{
    // NOTE(matt): Consider augmenting this to contain such stuff as: "hex signature"
    unsigned int       CurrentDBVersion; // NOTE(matt): Put this first to aid reliability
    version            CurrentAppVersion;
    version            CurrentHMMLVersion;

    unsigned int       InitialDBVersion;
    version            InitialAppVersion;
    version            InitialHMMLVersion;

    unsigned short int EntryCount;
    char               ProjectID[MAX_PROJECT_ID_LENGTH + 1];
    char               ProjectName[MAX_PROJECT_NAME_LENGTH + 1];
    char               BaseURL[MAX_BASE_URL_LENGTH + 1];
    char               IndexLocation[MAX_RELATIVE_PAGE_LOCATION_LENGTH + 1];
    char               PlayerLocation[MAX_RELATIVE_PAGE_LOCATION_LENGTH + 1];
    char               PlayerURLPrefix[MAX_PLAYER_URL_PREFIX_LENGTH + 1];
} index_header;

typedef struct
{
    unsigned int       PrevStart, NextStart;
    unsigned short int PrevEnd, NextEnd;
} link_insertion_offsets; // NOTE(matt): Relative

typedef struct
{
    link_insertion_offsets  LinkOffsets;
    unsigned short int      Size;
    char                    BaseFilename[MAX_BASE_FILENAME_LENGTH + 1];
    char                    Title[MAX_TITLE_LENGTH + 1];
} index_metadata;

typedef struct
{
    file_buffer File;
    file_buffer Metadata;
    index_header Header;
    index_metadata Entry;
} index;
// TODO(matt): Increment CINERA_DB_VERSION!

227 228 229 230 231 232 233 234 235
typedef struct
{
    buffer IncludesIndex;
    buffer Search;
    buffer Index; // NOTE(matt): This buffer is malloc'd separately, rather than claimed from the memory_arena
    buffer IncludesPlayer;
    buffer Menus;
    buffer Player;
    buffer ScriptPlayer;
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253

    char Custom0[MAX_CUSTOM_SNIPPET_SHORT_LENGTH + 1];
    char Custom1[MAX_CUSTOM_SNIPPET_SHORT_LENGTH + 1];
    char Custom2[MAX_CUSTOM_SNIPPET_SHORT_LENGTH + 1];
    char Custom3[MAX_CUSTOM_SNIPPET_SHORT_LENGTH + 1];
    char Custom4[MAX_CUSTOM_SNIPPET_SHORT_LENGTH + 1];
    char Custom5[MAX_CUSTOM_SNIPPET_SHORT_LENGTH + 1];
    char Custom6[MAX_CUSTOM_SNIPPET_SHORT_LENGTH + 1];
    char Custom7[MAX_CUSTOM_SNIPPET_SHORT_LENGTH + 1];
    char Custom8[MAX_CUSTOM_SNIPPET_SHORT_LENGTH + 1];
    char Custom9[MAX_CUSTOM_SNIPPET_SHORT_LENGTH + 1];
    char Custom10[MAX_CUSTOM_SNIPPET_SHORT_LENGTH + 1];
    char Custom11[MAX_CUSTOM_SNIPPET_SHORT_LENGTH + 1];
    char Custom12[MAX_CUSTOM_SNIPPET_LONG_LENGTH + 1];
    char Custom13[MAX_CUSTOM_SNIPPET_LONG_LENGTH + 1];
    char Custom14[MAX_CUSTOM_SNIPPET_LONG_LENGTH + 1];
    char Custom15[MAX_CUSTOM_SNIPPET_LONG_LENGTH + 1];

254 255 256 257
    char ProjectName[MAX_PROJECT_NAME_LENGTH + 1];
    char Title[MAX_TITLE_LENGTH + 1];
    char URLIndex[MAX_BASE_URL_LENGTH + 1 + MAX_RELATIVE_PAGE_LOCATION_LENGTH + 1];
    char URLPlayer[MAX_BASE_URL_LENGTH + 1 + MAX_RELATIVE_PAGE_LOCATION_LENGTH + 1 + MAX_PLAYER_URL_PREFIX_LENGTH + MAX_BASE_FILENAME_LENGTH + 1];
258 259 260
    char VideoID[16];
} buffers;

261 262
enum
{
263 264 265 266
    // Contents and Player Pages Mandatory
    TAG_INCLUDES,

    // Contents Page Mandatory
267 268
    TAG_INDEX,

269
    // Player Page Mandatory
270 271 272 273
    TAG_MENUS,
    TAG_PLAYER,
    TAG_SCRIPT,

274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
    // Player Page Optional
    TAG_CUSTOM0,
    TAG_CUSTOM1,
    TAG_CUSTOM2,
    TAG_CUSTOM3,
    TAG_CUSTOM4,
    TAG_CUSTOM5,
    TAG_CUSTOM6,
    TAG_CUSTOM7,
    TAG_CUSTOM8,
    TAG_CUSTOM9,
    TAG_CUSTOM10,
    TAG_CUSTOM11,

    TAG_CUSTOM12,
    TAG_CUSTOM13,
    TAG_CUSTOM14,
    TAG_CUSTOM15,

293 294
    TAG_TITLE,
    TAG_VIDEO_ID,
295 296 297 298

    // Anywhere Optional
    TAG_PROJECT,
    TAG_URL,
299 300 301 302 303 304 305 306 307 308
} template_tags;

typedef struct
{
    int Code; // template_tags
    char *Tag;
} tag;

tag Tags[] = {
    { TAG_INCLUDES, "__CINERA_INCLUDES__" },
309 310 311

    { TAG_INDEX,    "__CINERA_INDEX__" },

312 313 314
    { TAG_MENUS,    "__CINERA_MENUS__" },
    { TAG_PLAYER,   "__CINERA_PLAYER__" },
    { TAG_SCRIPT,   "__CINERA_SCRIPT__" },
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333

    { TAG_CUSTOM0,  "__CINERA_CUSTOM0__" },
    { TAG_CUSTOM1,  "__CINERA_CUSTOM1__" },
    { TAG_CUSTOM2,  "__CINERA_CUSTOM2__" },
    { TAG_CUSTOM3,  "__CINERA_CUSTOM3__" },
    { TAG_CUSTOM4,  "__CINERA_CUSTOM4__" },
    { TAG_CUSTOM5,  "__CINERA_CUSTOM5__" },
    { TAG_CUSTOM6,  "__CINERA_CUSTOM6__" },
    { TAG_CUSTOM7,  "__CINERA_CUSTOM7__" },
    { TAG_CUSTOM8,  "__CINERA_CUSTOM8__" },
    { TAG_CUSTOM9,  "__CINERA_CUSTOM9__" },
    { TAG_CUSTOM10,  "__CINERA_CUSTOM10__" },
    { TAG_CUSTOM11,  "__CINERA_CUSTOM11__" },

    { TAG_CUSTOM12,  "__CINERA_CUSTOM12__" },
    { TAG_CUSTOM13,  "__CINERA_CUSTOM13__" },
    { TAG_CUSTOM14,  "__CINERA_CUSTOM14__" },
    { TAG_CUSTOM15,  "__CINERA_CUSTOM15__" },

334
    { TAG_TITLE,    "__CINERA_TITLE__" },
335
    { TAG_VIDEO_ID, "__CINERA_VIDEO_ID__" },
336 337 338

    { TAG_PROJECT,  "__CINERA_PROJECT__" },
    { TAG_URL,      "__CINERA_URL__" },
339 340 341 342 343 344 345 346 347 348
};

typedef struct
{
    int Offset;
    int TagCode;
} tag_offset;

typedef struct
{
Matt Mascarenhas's avatar
Matt Mascarenhas committed
349
    char Filename[256];
350 351 352
    tag_offset Tag[16];
    int Validity; // NOTE(matt): Bitmask describing which page the template is valid for, i.e. contents and / or player page
    int TagCount;
353 354 355 356 357 358
} template_metadata;

typedef struct
{
    template_metadata Metadata;
    buffer Buffer;
359 360
} template;

361 362 363 364 365 366 367 368
// TODO(matt): Consider putting the ref_info and quote_info into linked lists on the heap, just to avoid all the hardcoded sizes

typedef struct
{
    char Date[32];
    char Text[512];
} quote_info;

369 370
typedef struct
{
371 372 373 374
    char Timecode[8];
    int Identifier;
} identifier;

375
#define REF_MAX_IDENTIFIER 64
376

377 378
typedef struct
{
379 380 381 382
    char RefTitle[620];
    char ID[512];
    char URL[512];
    char Source[256];
383
    identifier Identifier[REF_MAX_IDENTIFIER];
384
    int IdentifierCount;
385 386
} ref_info;

387 388
typedef struct
{
389 390
    char Marker[32];
    char WrittenText[32];
391
} category_info;
392

393 394 395 396 397 398
typedef struct
{
    category_info Category[64];
    int Count;
} categories;

399
// TODO(matt): Parse this stuff out of a config file
400 401 402 403 404 405 406 407 408 409
typedef struct
{
    char *Username;
    char *CreditedName;
    char *HomepageURL;
    char *SupportIcon;
    char *SupportURL;
} credential_info;

credential_info Credentials[] =
410
{
411 412
    { "/a_waterman", "Andrew Waterman", "https://www.linkedin.com/in/andrew-waterman-76805788", "", ""},
    { "/y_lee", "Yunsup Lee", "https://www.linkedin.com/in/yunsup-lee-385b692b/", "", ""},
413
    { "AndrewJDR", "Andrew Johnson", "", "", ""},
414
    { "AsafGartner", "Asaf Gartner", "", "", ""},
415 416 417
    { "BretHudson", "Bret Hudson", "http://www.brethudson.com/", "cinera_sprite_patreon.png", "https://www.patreon.com/indieFunction"},
    { "ChronalDragon", "Andrew Chronister", "http://chronal.net/", "", ""},
    { "Kelimion", "Jeroen van Rijn", "https://handmade.network/home", "", ""},
418
    { "Mannilie", "Emmanuel Vaccaro", "http://emmanuelvaccaro.com/", "", ""},
419
    { "Miblo", "Matt Mascarenhas", "https://miblodelcarpio.co.uk/", "cinera_sprite_sendowl.png", "https://miblodelcarpio.co.uk/cinera#pledge"},
420 421
    { "Mr4thDimention", "Allen Webster", "http://www.4coder.net/", "", ""},
    { "Quel_Solaar", "Eskil Steenberg", "http://quelsolaar.com/", "", ""},
422
    { "ZedZull", "Jay Waggle", "", "", ""},
423
    { "abnercoimbre", "Abner Coimbre", "https://handmade.network/m/abnercoimbre", "", ""},
424
    { "brianwill", "Brian Will", "http://brianwill.net/blog/", "", ""},
425
    { "cbloom", "Charles Bloom", "http://cbloomrants.blogspot.co.uk/", "", ""},
Matt Mascarenhas's avatar
Matt Mascarenhas committed
426
    { "cmuratori", "Casey Muratori", "https://handmadehero.org", "cinera_sprite_sendowl.png", "https://handmadehero.org/patreon.html"},
427
    { "csnover", "Colin Snover", "https://zetafleet.com/", "", ""},
428
    { "debiatan", "Miguel Lechón", "http://blog.debiatan.net/", "", ""},
429 430 431
    { "dspecht", "Dustin Specht", "", "", ""},
    { "effect0r", "Cory Henderlite", "", "", ""},
    { "ffsjs", "ffsjs", "", "", ""},
432 433
    { "fierydrake", "Mike Tunnicliffe", "", "", ""},
    { "garlandobloom", "Matthew VanDevander", "https://lowtideproductions.com/", "cinera_sprite_patreon.png", "https://www.patreon.com/mv"},
434 435 436
    { "ikerms", "Iker Murga", "", "", ""},
    { "insofaras", "Alex Baines", "https://abaines.me.uk/", "", ""},
    { "jacebennett", "Jace Bennett", "", "", ""},
437
    { "jon", "Jonathan Blow", "http://the-witness.net/news/", "", ""},
438
    { "jpike", "Jacob Pike", "", "", ""},
439
    { "martincohen", "Martin Cohen", "http://blog.coh.io/", "", ""},
440 441 442
    { "miotatsu", "Mio Iwakura", "http://riscy.tv/", "cinera_sprite_patreon.png", "https://patreon.com/miotatsu"},
    { "nothings", "Sean Barrett", "https://nothings.org/", "", ""},
    { "philipbuuck", "Philip Buuck", "http://philipbuuck.com/", "", ""},
443
    { "powerc9000", "Clay Murray", "http://claymurray.website/", "", ""},
444
    { "rygorous", "Fabian Giesen", "https://fgiesen.wordpress.com/", "", ""},
445
    { "schme", "Kasper Sauramo", "", "", ""},
446 447
    { "sssmcgrath", "Shawn McGrath", "http://www.dyadgame.com/", "", ""},
    { "thehappiecat", "Anne", "https://www.youtube.com/c/TheHappieCat", "cinera_sprite_patreon.png", "https://www.patreon.com/thehappiecat"},
448
    { "theinternetftw", "Ben Craddock", "", "", ""},
449
    { "wheatdog", "Tim Liou", "http://stringbulbs.com/", "", ""},
450 451
    { "williamchyr", "William Chyr", "http://williamchyr.com/", "", ""},
    { "wonchun", "Won Chun", "https://twitter.com/won3d", "", ""},
452 453 454 455 456 457 458 459 460 461 462 463
};

typedef struct
{
    char *Medium;
    char *Icon;
    char *WrittenName;
} category_medium;

category_medium CategoryMedium[] =
{
    // medium        icon         written name
464
    { "admin",       "&#128505;", "Administrivia"},
465
    { "afk",         "&#8230;"  , "Away from Keyboard"},
466 467 468
    { "authored",    "&#128490;", "Chat Comment"}, // TODO(matt): Conditionally handle Chat vs Guest Comments
    { "blackboard",  "&#128396;", "Blackboard"},
    { "experience",  "&#127863;", "Experience"},
469 470
    { "hat",         "&#127913;", "Hat"},
    { "multimedia",  "&#127916;", "Media Clip"},
471 472 473 474 475
    { "owl",         "&#129417;", "Owl of Shame"},
    { "programming", "&#128430;", "Programming"}, // TODO(matt): Potentially make this configurable per project
    { "rant",        "&#128162;", "Rant"},
    { "research",    "&#128214;", "Research"},
    { "run",         "&#127939;", "In-Game"}, // TODO(matt): Potentially make this configurable per project
476
    { "speech",      "&#128489;", "Speech"},
477
    { "trivia",      "&#127922;", "Trivia"},
478 479
};

Matt Mascarenhas's avatar
Matt Mascarenhas committed
480 481 482 483 484 485 486 487 488 489 490 491
enum
{
    NS_CALENDRICAL,
    NS_LINEAR,
    NS_SEASONAL,
} numbering_schemes;

typedef struct
{
    char *ProjectID;
    char *FullName;
    char *Unit; // e.g. Day, Episode, Session
492 493 494
    int NumberingScheme; // numbering_schemes
    char *Medium;
    char *AltURLPrefix; // NOTE(matt): This currently just straight up replaces the ProjectID in the player pages' output directories
Matt Mascarenhas's avatar
Matt Mascarenhas committed
495 496 497 498
} project_info;

project_info ProjectInfo[] =
{
499 500 501
    { "book",  "Book Club",      "Day", NS_LINEAR, "research",    "" },
    { "pcalc", "pcalc",          "Day", NS_LINEAR, "programming", "" },
    { "riscy", "RISCY BUSINESS", "Day", NS_LINEAR, "programming", "" },
502

503 504 505 506 507
    { "chat",       "Handmade Chat",         "Day", NS_LINEAR, "speech",      "" },
    { "code",       "Handmade Hero",         "Day", NS_LINEAR, "programming", "day" },
    { "intro-to-c", "Intro to C on Windows", "Day", NS_LINEAR, "programming", "day" },
    { "misc",       "Handmade Miscellany",   "",    NS_LINEAR, "admin",       "" },
    { "ray",        "Handmade Ray",          "Day", NS_LINEAR, "programming", "" },
508

509 510 511 512
    { "hmdshow", "HandmadeDev Show",   "", NS_SEASONAL, "speech",      "ep" },
    { "lecture", "Abner Talks",        "", NS_SEASONAL, "speech",      "" },
    { "stream",  "Abner Programs",     "", NS_SEASONAL, "programming", "" },
    { "special", "Abner Show Special", "", NS_SEASONAL, "programming", "" },
513

514
    { "obbg", "Open Block Building Game", "Episode", NS_LINEAR, "programming", "" },
515

516
    { "sysadmin", "SysAdmin", "Session", NS_LINEAR, "admin", "" },
Matt Mascarenhas's avatar
Matt Mascarenhas committed
517 518
};

519 520
#define ArrayCount(A) sizeof(A)/sizeof(*(A))

521
__attribute__ ((format (printf, 2, 3)))
Matt Mascarenhas's avatar
Matt Mascarenhas committed
522
int
523
CopyString(char Dest[], char *Format, ...)
524
{
Matt Mascarenhas's avatar
Matt Mascarenhas committed
525
    int Length = 0;
526 527
    va_list Args;
    va_start(Args, Format);
Matt Mascarenhas's avatar
Matt Mascarenhas committed
528
    Length = vsprintf(Dest, Format, Args);
529
    va_end(Args);
Matt Mascarenhas's avatar
Matt Mascarenhas committed
530
    return Length;
531 532
}

533
int
534
StringLength(char *String)
535
{
536 537
    int i = 0;
    while(String[i])
538
    {
539
        ++i;
540
    }
541
    return i;
542 543
}

544
void
545
CopyBuffer(buffer *Dest, buffer *Src)
546 547 548 549
{
    Src->Ptr = Src->Location;
    while(*Src->Ptr)
    {
550 551 552 553
        // TODO(matt)
        {
            if(Dest->Ptr - Dest->Location >= Dest->Size)
            {
554
                fprintf(stderr, "CopyBuffer: %s cannot accommodate %s\n", Dest->ID, Src->ID);
555 556 557
                __asm__("int3");
            }
        }
558 559
        *Dest->Ptr++ = *Src->Ptr++;
    }
560
    *Dest->Ptr = '\0';
561 562
}

563 564 565 566 567 568 569 570 571
void
Clear(char *String, int Size)
{
    for(int i = 0; i < Size; ++i)
    {
        String[i] = 0;
    }
}

572
int
573 574
CopyStringNoFormat(char *Dest, char *String)
{
575
    int Length = 0;
576 577 578
    while(*String)
    {
        *Dest++ = *String++;
579
        ++Length;
580
    }
581
    *Dest = '\0';
582
    return Length;
583 584
}

585 586 587 588 589 590 591
int
ClearCopyStringNoFormat(char *Dest, int DestSize, char *String)
{
    Clear(Dest, DestSize);
    return(CopyStringNoFormat(Dest, String));
}

592
// TODO(matt): Maybe do a version of this that takes a string as a Terminator
593 594 595 596 597 598 599 600 601 602 603 604 605
int
CopyStringNoFormatT(char *Dest, char *String, char Terminator)
{
    int Length = 0;
    while(*String != Terminator)
    {
        *Dest++ = *String++;
        ++Length;
    }
    *Dest = '\0';
    return Length;
}

606
__attribute__ ((format (printf, 2, 3)))
607
void
608
CopyStringToBuffer(buffer *Dest, char *Format, ...)
609
{
610 611
    va_list Args;
    va_start(Args, Format);
612
    int Length = vsnprintf(Dest->Ptr, Dest->Size - (Dest->Ptr - Dest->Location), Format, Args);
613
    va_end(Args);
Matt Mascarenhas's avatar
Matt Mascarenhas committed
614
    // TODO(matt)
615 616 617
    {
        if(Length + (Dest->Ptr - Dest->Location) >= Dest->Size)
        {
618 619
            fprintf(stderr, "CopyStringToBuffer: %s cannot accommodate %d-character string:\n"
                    "\n"
620
                    "%s\n", Dest->ID, Length, Format);
621 622 623
            __asm__("int3");
        }
    }
624
    Dest->Ptr += Length;
625 626
}

627 628 629 630 631 632 633 634 635 636
void
CopyStringToBufferNoFormat(buffer *Dest, char *String)
{
    while(*String)
    {
        *Dest->Ptr++ = *String++;
    }
    *Dest->Ptr = '\0';
}

637 638 639 640 641 642 643 644 645 646 647 648 649
void
CopyStringToBufferHTMLSafe(buffer *Dest, char *String)
{
    while(*String)
    {
        if(Dest->Ptr - Dest->Location >= Dest->Size)
        {
            fprintf(stderr, "CopyStringToBufferHTMLSafe: %s cannot accommodate %d-character string\n", Dest->ID, StringLength(String));
            __asm__("int3");
        }
        switch(*String)
        {
            case '<':
650 651 652
            CopyStringToBuffer(Dest, "&lt;");
            String++;
            break;
653
            case '>':
654 655 656
            CopyStringToBuffer(Dest, "&gt;");
            String++;
            break;
657
            case '&':
658 659 660
            CopyStringToBuffer(Dest, "&amp;");
            String++;
            break;
661
            case '\"':
662 663 664
            CopyStringToBuffer(Dest, "&quot;");
            String++;
            break;
665
            case '\'':
666 667 668
            CopyStringToBuffer(Dest, "&#39;");
            String++;
            break;
669
            default:
670 671
            *Dest->Ptr++ = *String++;
            break;
672 673 674 675
        }
    }
}

Matt Mascarenhas's avatar
Matt Mascarenhas committed
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
void
CopyStringToBufferJSONSafe(buffer *Dest, char *String)
{
    while(*String)
    {
        if(Dest->Ptr - Dest->Location >= Dest->Size)
        {
            fprintf(stderr, "CopyStringToBufferHTMLSafe: %s cannot accommodate %d-character string\n", Dest->ID, StringLength(String));
            __asm__("int3");
        }
        switch(*String)
        {
            case '\\':
            case '\"':
                *Dest->Ptr++ = '\\';
            default:
                *Dest->Ptr++ = *String++;
                break;
        }
    }
}

698
int
699
StringsDiffer(char *A, char *B) // NOTE(matt): Two null-terminated strings
700
{
701
    while(*A && *B && *A == *B)
702 703 704 705 706 707
    {
        ++A, ++B;
    }
    return *A - *B;
}

708
bool
709 710
StringsDifferT(char *A, // NOTE(matt): Null-terminated string
               char *B, // NOTE(matt): Not null-terminated string (e.g. one mid-buffer)
711
               char Terminator // NOTE(matt): Caller definable terminator. Pass 0 to only match on the extent of A
712
               )
713
{
714
    int ALength = StringLength(A);
715
    int i = 0;
716
    while(i < ALength && A[i] && A[i] == B[i])
717 718 719
    {
        ++i;
    }
720
    if((!Terminator && !A[i] && ALength == i) ||
721
       (!A[i] && ALength == i && (B[i] == Terminator)))
722 723 724 725 726 727 728 729 730
    {
        return FALSE;
    }
    else
    {
        return TRUE;
    }
}

731 732 733
int
MakeDir(char *Path)
{
734
    // TODO(matt): Correctly check for permissions
735 736 737 738
    int i = StringLength(Path);
    int Ancestors = 0;
    while(mkdir(Path, 00755) == -1)
    {
739 740 741 742
        if(errno == EACCES)
        {
            return RC_ERROR_DIRECTORY;
        }
743 744 745 746 747 748
        while(Path[i] != '/' && i > 0)
        {
            --i;
        }
        ++Ancestors;
        Path[i] = '\0';
749
        if(i == 0) { return RC_ERROR_DIRECTORY; }
750 751 752 753 754 755 756 757 758 759 760
    }
    while(Ancestors > 0)
    {
        while(Path[i] != '\0')
        {
            ++i;
        }
        Path[i] = '/';
        --Ancestors;
        if((mkdir(Path, 00755)) == -1)
        {
761
            return RC_ERROR_DIRECTORY;
762 763
        }
    }
764 765 766 767
    return RC_SUCCESS;
}

void
768
LogUsage(buffer *Buffer)
769
{
770
#if DEBUG
Matt Mascarenhas's avatar
Matt Mascarenhas committed
771
    char LogPath[256];
772
    CopyString(LogPath, "%s/%s", Config.CacheDir, "buffers.log");
773 774 775
    FILE *LogFile;
    if(!(LogFile = fopen(LogPath, "a+")))
    {
776
        MakeDir(Config.CacheDir);
777 778 779 780 781 782 783 784
        if(!(LogFile = fopen(LogPath, "a+")))
        {
            perror("LogUsage");
            return;
        }
    }

    fprintf(LogFile, "%s,%ld,%d\n",
785 786 787
            Buffer->ID,
            Buffer->Ptr - Buffer->Location,
            Buffer->Size);
788
    fclose(LogFile);
789
#endif
790 791
}

792
__attribute__ ((format (printf, 2, 3)))
793
void
794
LogError(int LogLevel, char *Format, ...)
795 796 797
{
    if(Config.LogLevel >= LogLevel)
    {
Matt Mascarenhas's avatar
Matt Mascarenhas committed
798
        char LogPath[256];
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
        CopyString(LogPath, "%s/%s", Config.CacheDir, "errors.log");
        FILE *LogFile;
        if(!(LogFile = fopen(LogPath, "a+")))
        {
            MakeDir(Config.CacheDir);
            if(!(LogFile = fopen(LogPath, "a+")))
            {
                perror("LogUsage");
                return;
            }
        }

        va_list Args;
        va_start(Args, Format);
        vfprintf(LogFile, Format, Args);
        va_end(Args);
        // TODO(matt): Include the LogLevel "string" and the current wall time
        fprintf(LogFile, "\n");
        fclose(LogFile);
    }
819 820 821 822 823 824
}

void
FreeBuffer(buffer *Buffer)
{
    free(Buffer->Location);
Matt Mascarenhas's avatar
Matt Mascarenhas committed
825
    Buffer->Location = '\0';
826 827 828 829 830 831
#if DEBUG_MEM
    FILE *MemLog = fopen("/home/matt/cinera_mem", "a+");
    fprintf(MemLog, "     Freed %s\n", Buffer->ID);
    fclose(MemLog);
    printf("     Freed %s\n", Buffer->ID);
#endif
832 833
}

834 835
#if 0
#define ClaimBuffer(MemoryArena, Buffer, ID, Size) if(__ClaimBuffer(MemoryArena, Buffer, ID, Size))\
836 837 838 839 840 841
{\
    fprintf(stderr, "%s:%d: MemoryArena cannot contain %s of size %d\n", __FILE__, __LINE__, ID, Size);\
    hmml_free(&HMML);\
    FreeBuffer(MemoryArena);\
    return 1;\
};
842
#endif
843 844

int
845
ClaimBuffer(buffer *Buffer, char *ID, int Size)
846
{
847
    if(MemoryArena.Ptr - MemoryArena.Location + Size > MemoryArena.Size)
848
    {
849
        return RC_ARENA_FULL;
850
    }
851
    Buffer->Location = (char *)MemoryArena.Ptr;
852 853
    Buffer->Size = Size;
    Buffer->ID = ID;
854
    MemoryArena.Ptr += Buffer->Size;
855 856 857
    *Buffer->Location = '\0';
    Buffer->Ptr = Buffer->Location;
#if DEBUG
858
    float PercentageUsed = (float)(MemoryArena.Ptr - MemoryArena.Location) / MemoryArena.Size * 100;
859
    printf("  ClaimBuffer(%s): %d\n"
860
           "    Total ClaimedMemory: %ld (%.2f%%, leaving %ld free)\n\n", Buffer->ID, Buffer->Size, MemoryArena.Ptr - MemoryArena.Location, PercentageUsed, MemoryArena.Size - (MemoryArena.Ptr - MemoryArena.Location));
861
#endif
862
    return RC_SUCCESS;
863 864 865
}

void
866
DeclaimBuffer(buffer *Buffer)
867 868
{
    *Buffer->Location = '\0';
869
    MemoryArena.Ptr -= Buffer->Size;
870 871
    float PercentageUsed = (float)(Buffer->Ptr - Buffer->Location) / Buffer->Size * 100;
#if DEBUG
872
    printf("DeclaimBuffer(%s)\n"
873 874
           "    Used: %ld / %d (%.2f%%)\n"
           "\n"
875
           "    Total ClaimedMemory: %ld\n\n",
876 877 878 879
           Buffer->ID,
           Buffer->Ptr - Buffer->Location,
           Buffer->Size,
           PercentageUsed,
880
           MemoryArena.Ptr - MemoryArena.Location);
881
#endif
882
    LogUsage(Buffer);
883 884 885
    if(PercentageUsed >= 80.0f)
    {
        // TODO(matt): Implement either dynamically growing buffers, or phoning home to [email protected]
886
        LogError(LOG_ERROR, "%s used %.2f%% of its allotted memory\n", Buffer->ID, PercentageUsed);
887 888
        fprintf(stderr, "Warning: %s used %.2f%% of its allotted memory\n", Buffer->ID, PercentageUsed);
    }
Matt Mascarenhas's avatar
Matt Mascarenhas committed
889
    Buffer->Size = 0;
890 891
}

892 893 894 895 896 897 898 899 900 901 902 903 904 905
void RewindBuffer(buffer *Buffer)
{
#if DEBUG
    float PercentageUsed = (float)(Buffer->Ptr - Buffer->Location) / Buffer->Size * 100;
    printf("Rewinding %s\n"
                    "    Used: %ld / %d (%.2f%%)\n\n",
                    Buffer->ID,
                    Buffer->Ptr - Buffer->Location,
                    Buffer->Size,
                    PercentageUsed);
#endif
    Buffer->Ptr = Buffer->Location;
}

906 907 908 909 910 911 912
enum
{
    TEMPLATE_INDEX,
    TEMPLATE_PLAYER,
    TEMPLATE_BESPOKE
} templates;

913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
char *
GetDirectoryPath(char *Filepath)
{
    char *Ptr = Filepath + StringLength(Filepath) - 1;
    while(Ptr > Filepath && *Ptr != '/')
    {
        --Ptr;
    }
    if(Ptr == Filepath)
    {
        *Ptr++ = '.';
    }
    *Ptr = '\0';
    return Filepath;
}

char *
GetBaseFilename(char *Filepath,
        char *Extension // Including the "."
                        // Pass 0 to retain the whole file path, only without its parent directories
        )
{
    char *BaseFilename = Filepath + StringLength(Filepath) - 1;
    while(BaseFilename > Filepath && *BaseFilename != '/')
    {
        --BaseFilename;
    }
    if(*BaseFilename == '/')
    {
        ++BaseFilename;
    }
    BaseFilename[StringLength(BaseFilename) - StringLength(Extension)] = '\0';
    return BaseFilename;
}

948 949 950
void
ConstructTemplatePath(template *Template, int TemplateType)
{
951 952 953 954
    // NOTE(matt): Bespoke template paths are set relative to:
    //                  in Project Edition: ProjectDir
    //                  in Single  Edition: Parent directory of .hmml file

955 956 957 958 959 960 961
    if(Template->Metadata.Filename[0] != '/')
    {
        char Temp[256];
        CopyString(Temp, Template->Metadata.Filename);
        char *Ptr = Template->Metadata.Filename;
        if(TemplateType == TEMPLATE_BESPOKE)
        {
962 963 964 965 966 967 968 969
            if(Config.Edition == EDITION_SINGLE)
            {
                Ptr += CopyString(Ptr, "%s/", GetDirectoryPath(Config.SingleHMMLFilePath));
            }
            else
            {
                Ptr += CopyString(Ptr, "%s/", Config.ProjectDir);
            }
970 971 972 973 974 975 976 977 978
        }
        else
        {
            Ptr += CopyString(Ptr, "%s/", Config.TemplatesDir);
        }
        CopyString(Ptr, "%s", Temp);
    }
}

979
int
980
InitTemplate(template **Template)
981
{
982 983 984 985
    if(MemoryArena.Ptr - MemoryArena.Location + sizeof(template) > MemoryArena.Size)
    {
        return RC_ARENA_FULL;
    }
986
    *Template = (template *)MemoryArena.Ptr;
987 988 989 990
    Clear((*Template)->Metadata.Filename, 256); // NOTE(matt): template_metadata specifies Filename[256]
    (*Template)->Metadata.Validity = 0;
    (*Template)->Metadata.TagCount = 0;
    for(int i = 0; i < 16; ++i) // NOTE(matt): template_metadata specifies Tag[16]
991
    {
992 993
        (*Template)->Metadata.Tag[i].Offset = 0;
        (*Template)->Metadata.Tag[i].TagCode = 0;
994
    }
995 996 997 998 999 1000 1001 1002 1003 1004 1005
    MemoryArena.Ptr += sizeof(template);
    return RC_SUCCESS;
}

int
ClaimTemplate(template **Template, char *Location, int TemplateType)
{
    CopyString((*Template)->Metadata.Filename, Location);
    ConstructTemplatePath((*Template), TemplateType);

    if(TemplateType == TEMPLATE_BESPOKE)
1006
    {
1007
        fprintf(stderr, "\e[0;35mPacking\e[0m template: %s\n", (*Template)->Metadata.Filename);
1008
    }
1009 1010 1011 1012 1013 1014

    FILE *File;
    if(!(File = fopen((*Template)->Metadata.Filename, "r")))
    {
        LogError(LOG_ERROR, "Unable to open template %s: %s", (*Template)->Metadata.Filename, strerror(errno));
        fprintf(stderr, "Unable to open template %s: %s\n", (*Template)->Metadata.Filename, strerror(errno));
1015
        Clear((*Template)->Metadata.Filename, 256); // NOTE(matt): template_metadata specifies Filename[256]
1016 1017 1018 1019
        return RC_ERROR_FILE;
    }
    fseek(File, 0, SEEK_END);
    (*Template)->Buffer.Size = ftell(File);
1020
    if(MemoryArena.Ptr - MemoryArena.Location + (*Template)->Buffer.Size > MemoryArena.Size)
1021
    {
1022
        Clear((*Template)->Metadata.Filename, 256); // NOTE(matt): template_metadata specifies Filename[256]
1023 1024
        return RC_ARENA_FULL;
    }
1025

1026 1027 1028
    (*Template)->Buffer.Location = MemoryArena.Ptr;
    (*Template)->Buffer.Ptr = (*Template)->Buffer.Location;
    (*Template)->Buffer.ID = (*Template)->Metadata.Filename;
1029 1030 1031 1032 1033

    fseek(File, 0, SEEK_SET);
    fread((*Template)->Buffer.Location, (*Template)->Buffer.Size, 1, File);
    fclose(File);

1034 1035
    MemoryArena.Ptr += (*Template)->Buffer.Size;

1036
#if DEBUG
1037 1038
    printf("  ClaimTemplate(%s): %d\n"
           "    Total ClaimedMemory: %ld\n\n", (*Template)->Metadata.Filename, (*Template)->Buffer.Size, MemoryArena.Ptr - MemoryArena.Location);
1039 1040 1041 1042 1043
#endif
    return RC_SUCCESS;
}

int
1044
DeclaimTemplate(template *Template)
1045
{
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
    Clear(Template->Metadata.Filename, 256);
    Template->Metadata.Validity = 0;
    for(int i = 0; i < Template->Metadata.TagCount; ++i)
    {
        Template->Metadata.Tag[i].Offset = 0;
        Template->Metadata.Tag[i].TagCode = 0;
    }
    Template->Metadata.TagCount = 0;
    MemoryArena.Ptr -= (*Template).Buffer.Size;

1056
#if DEBUG
1057
    printf("DeclaimTemplate(%s)\n"
1058
           "    Total ClaimedMemory: %ld\n\n",
1059 1060
           (*Template).Metadata.Filename,
           MemoryArena.Ptr - MemoryArena.Location);
1061 1062 1063 1064
#endif
    return RC_SUCCESS;
}

1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
int
TimecodeToSeconds(char *Timecode)
{
    int HMS[3] = { 0, 0, 0 }; // 0 == Seconds; 1 == Minutes; 2 == Hours
    int Colons = 0;
    while(*Timecode)
    {
        //if((*Timecode < '0' || *Timecode > '9') && *Timecode != ':') { return FALSE; }

        if(*Timecode == ':')
        {
            ++Colons;
            //if(Colons > 2) { return FALSE; }
            for(int i = 0; i < Colons; ++i)
            {
                HMS[Colons - i] = HMS[Colons - (i + 1)];
            }
            HMS[0] = 0;
        }
        else
        {
            HMS[0] = HMS[0] * 10 + *Timecode - '0';
        }

        ++Timecode;
    }

    //if(HMS[0] > 59 || HMS[1] > 59 || Timecode[-1] == ':') { return FALSE; }

    return HMS[2] * 60 * 60 + HMS[1] * 60 + HMS[0];
}

1097 1098
typedef struct
{
1099 1100 1101
    unsigned int Hue:16;
    unsigned int Saturation:8;
    unsigned int Lightness:8;
1102 1103 1104
} hsl_colour;

hsl_colour
1105 1106
CharToColour(char Char)
{
1107
    hsl_colour Colour;
1108 1109
    if(Char >= 'a' && Char <= 'z')
    {
1110 1111
        Colour.Hue = (((float)Char - 'a') / ('z' - 'a') * 360);
        Colour.Saturation = (((float)Char - 'a') / ('z' - 'a') * 26 + 74);
1112 1113 1114
    }
    else if(Char >= 'A' && Char <= 'Z')
    {
1115 1116
        Colour.Hue = (((float)Char - 'A') / ('Z' - 'A') * 360);
        Colour.Saturation = (((float)Char - 'A') / ('Z' - 'A') * 26 + 74);
1117 1118 1119
    }
    else if(Char >= '0' && Char <= '9')
    {
1120 1121
        Colour.Hue = (((float)Char - '0') / ('9' - '0') * 360);
        Colour.Saturation = (((float)Char - '0') / ('9' - '0') * 26 + 74);
1122 1123 1124
    }
    else
    {
1125 1126
        Colour.Hue = 180;
        Colour.Saturation = 50;
1127
    }
1128

1129
    return Colour;
1130 1131
}

1132 1133
hsl_colour *
StringToColourHash(hsl_colour *Colour, char *String)
1134
{
1135 1136
    Colour->Hue = 0;
    Colour->Saturation = 0;
Matt Mascarenhas's avatar
Matt Mascarenhas committed
1137
    Colour->Lightness = 74;
1138

1139 1140 1141
    int i;
    for(i = 0; String[i]; ++i)
    {
1142 1143
        Colour->Hue += CharToColour(String[i]).Hue;
        Colour->Saturation += CharToColour(String[i]).Saturation;
1144
    }
1145

1146 1147 1148
    Colour->Hue = Colour->Hue % 360;
    Colour->Saturation = Colour->Saturation % 26 + 74;
    return(Colour);
1149 1150
}

1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161
char *
SanitisePunctuation(char *String)
{
    char *Ptr = String;
    while(*Ptr)
    {
        if(*Ptr == ' ')
        {
            *Ptr = '_';
        }
        if((*Ptr < '0' || *Ptr > '9') &&
1162 1163
           (*Ptr < 'a' || *Ptr > 'z') &&
           (*Ptr < 'A' || *Ptr > 'Z'))
1164 1165 1166 1167 1168 1169 1170 1171
        {
            *Ptr = '-';
        }
        ++Ptr;
    }
    return String;
}

1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
enum
{
    INCLUDE_CSS,
    INCLUDE_Images,
    INCLUDE_JS,
} include_types;

enum
{
    PAGE_PLAYER = 1 << 0,
    PAGE_INDEX = 1 << 1
} pages;

void
ConstructURLPrefix(buffer *URLPrefix, int IncludeType, int PageType)
{
1188
    RewindBuffer(URLPrefix);
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
    if(StringsDiffer(Config.RootURL, ""))
    {
        URLPrefix->Ptr += CopyString(URLPrefix->Ptr, "%s/", Config.RootURL);
    }
    else
    {
        if(Config.Edition == EDITION_PROJECT)
        {
            if(PageType == PAGE_PLAYER)
            {
                URLPrefix->Ptr += CopyString(URLPrefix->Ptr, "../");
            }
            URLPrefix->Ptr += CopyString(URLPrefix->Ptr, "../");
        }
    }

    switch(IncludeType)
    {
        case INCLUDE_CSS:
            if(StringsDiffer(Config.CSSDir, ""))
            {
                URLPrefix->Ptr += CopyString(URLPrefix->Ptr, "%s/", Config.CSSDir);
            }
            break;
        case INCLUDE_Images:
            if(StringsDiffer(Config.ImagesDir, ""))
            {
                URLPrefix->Ptr += CopyString(URLPrefix->Ptr, "%s/", Config.ImagesDir);
            }
            break;
        case INCLUDE_JS:
            if(StringsDiffer(Config.JSDir, ""))
            {
                URLPrefix->Ptr += CopyString(URLPrefix->Ptr, "%s/", Config.JSDir);
            }
            break;
    }
}

1228
enum
1229
{
1230 1231 1232
    CreditsError_NoHost,
    CreditsError_NoAnnotator,
    CreditsError_NoCredentials
Matt Mascarenhas's avatar
Matt Mascarenhas committed
1233
} credits_errors;
1234

1235
int
1236
SearchCredentials(buffer *CreditsMenu, bool *HasCreditsMenu, char *Person, char *Role)
1237 1238
{
    bool Found = FALSE;
1239 1240
    for(int CredentialIndex = 0; CredentialIndex < ArrayCount(Credentials); ++CredentialIndex)
    {
1241
        if(!StringsDiffer(Person, Credentials[CredentialIndex].Username))
1242
        {
1243 1244 1245 1246
            Found = TRUE;
            if(*HasCreditsMenu == FALSE)
            {
                CopyStringToBuffer(CreditsMenu,
Matt Mascarenhas's avatar
Matt Mascarenhas committed
1247 1248 1249 1250
                        "            <div class=\"menu credits\">\n"
                        "                <div class=\"mouse_catcher\"></div>\n"
                        "                <span>Credits</span>\n"
                        "                <div class=\"credits_container\">\n");
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266

                *HasCreditsMenu = TRUE;
            }

            CopyStringToBuffer(CreditsMenu,
                    "                    <span class=\"credit\">\n");
            if(*Credentials[CredentialIndex].HomepageURL)
            {
                CopyStringToBuffer(CreditsMenu,
                        "                        <a class=\"person\" href=\"%s\" target=\"_blank\">\n"
                        "                            <div class=\"role\">%s</div>\n"
                        "                            <div class=\"name\">%s</div>\n"
                        "                        </a>\n",
                        Credentials[CredentialIndex].HomepageURL,
                        Role,
                        Credentials[CredentialIndex].CreditedName);
1267 1268 1269
            }
            else
            {
1270 1271 1272 1273 1274 1275 1276
                CopyStringToBuffer(CreditsMenu,
                        "                        <div class=\"person\">\n"
                        "                            <div class=\"role\">%s</div>\n"
                        "                            <div class=\"name\">%s</div>\n"
                        "                        </div>\n",
                        Role,
                        Credentials[CredentialIndex].CreditedName);
1277
            }
1278

1279
            if(*Credentials[CredentialIndex].SupportIcon && *Credentials[CredentialIndex].SupportURL)
1280
            {
1281
                buffer URLPrefix;
1282
                ClaimBuffer(&URLPrefix, "URLPrefix", 1024);
1283
                ConstructURLPrefix(&URLPrefix, INCLUDE_Images, PAGE_PLAYER);
Matt Mascarenhas's avatar
Matt Mascarenhas committed
1284 1285 1286
                CopyStringToBuffer(CreditsMenu,
                        "                        <a class=\"support\" href=\"%s\" target=\"_blank\"><div class=\"support_icon\" style=\"background-image: url(%s%s);\"></div></a>\n",
                        Credentials[CredentialIndex].SupportURL,
1287
                        URLPrefix.Location,
Matt Mascarenhas's avatar
Matt Mascarenhas committed
1288
                        Credentials[CredentialIndex].SupportIcon);
1289
                DeclaimBuffer(&URLPrefix);
1290
            }
1291

1292 1293
            CopyStringToBuffer(CreditsMenu,
                    "                    </span>\n");
1294
        }
1295 1296 1297
    }
    return Found ? 0 : CreditsError_NoCredentials;
}
1298

1299
int
1300
BuildCredits(buffer *CreditsMenu, bool *HasCreditsMenu, HMML_VideoMetaData *Metadata)
Matt Mascarenhas's avatar
Matt Mascarenhas committed
1301
// TODO(matt): Make this take the Credentials, once we are parsing them from a config
1302
{
1303
    if(Metadata->member)
1304
    {
1305
        if(SearchCredentials(CreditsMenu, HasCreditsMenu, Metadata->member, "Host"))
1306
        {
1307
            printf("No credentials for member %s. Please contact [email protected] with their:\n"
1308 1309
                    "    Full name\n"
                    "    Homepage URL (optional)\n"
1310
                    "    Financial support info, e.g. Patreon URL (optional)\n", Metadata->member);
1311
            return CreditsError_NoCredentials;
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
        }
    }
    else
    {
        if(*HasCreditsMenu == TRUE)
        {
            CopyStringToBuffer(CreditsMenu,
                    "                </div>\n"
                    "            </div>\n");
        }
1322
        fprintf(stderr, "Missing \"member\" in the [video] node\n");
1323 1324 1325
        return CreditsError_NoHost;
    }

1326
    if(Metadata->co_host_count > 0)
1327
    {
1328
        for(int i = 0; i < Metadata->co_host_count; ++i)
1329
        {
1330
            if(SearchCredentials(CreditsMenu, HasCreditsMenu, Metadata->co_hosts[i], "Co-host"))
1331
            {
1332
                printf("No credentials for co-host %s. Please contact [email protected] with their:\n"
1333 1334
                        "    Full name\n"
                        "    Homepage URL (optional)\n"
1335
                        "    Financial support info, e.g. Patreon URL (optional)\n", Metadata->co_hosts[i]);
1336
                return CreditsError_NoCredentials;
1337
            }
1338 1339
        }
    }
1340

1341
    if(Metadata->guest_count > 0)
1342
    {
1343
        for(int i = 0; i < Metadata->guest_count; ++i)
1344
        {
1345
            if(SearchCredentials(CreditsMenu, HasCreditsMenu, Metadata->guests[i], "Guest"))
1346
            {
1347
                printf("No credentials for guest %s. Please contact [email protected] with their:\n"
1348 1349
                        "    Full name\n"
                        "    Homepage URL (optional)\n"
1350
                        "    Financial support info, e.g. Patreon URL (optional)\n", Metadata->guests[i]);
1351
                return CreditsError_NoCredentials;
1352 1353 1354
            }
        }
    }
1355

1356
    if(Metadata->annotator_count > 0)
1357
    {
1358
        for(int i = 0; i < Metadata->annotator_count; ++i)
1359
        {
1360
            if(SearchCredentials(CreditsMenu, HasCreditsMenu, Metadata->annotators[i], "Annotator"))
1361
            {
1362
                printf("No credentials for annotator %s. Please contact [email protected] with their:\n"
1363 1364
                        "    Full name\n"
                        "    Homepage URL (optional)\n"
1365
                        "    Financial support info, e.g. Patreon URL (optional)\n", Metadata->annotators[i]);
1366
                return CreditsError_NoCredentials;
1367
            }
1368
        }
1369 1370 1371 1372
    }
    else
    {
        if(*HasCreditsMenu == TRUE)
1373
        {
1374 1375 1376
            CopyStringToBuffer(CreditsMenu,
                    "                </div>\n"
                    "            </div>\n");
1377
        }
1378
        fprintf(stderr, "Missing \"annotator\" in the [video] node\n");
1379
        return CreditsError_NoAnnotator;
1380
    }
1381 1382

    if(*HasCreditsMenu == TRUE)
1383
    {
1384 1385 1386
        CopyStringToBuffer(CreditsMenu,
                "                </div>\n"
                "            </div>\n");
1387
    }
1388

1389
    return RC_SUCCESS;
1390 1391
}

1392
int
1393
BuildReference(ref_info *ReferencesArray, int RefIdentifier, int UniqueRefs, HMML_Reference *Ref, HMML_Annotation *Anno)
1394
{
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407

#define REF_SITE (1 << 0)
#define REF_PAGE (1 << 1)
#define REF_URL (1 << 2)
#define REF_TITLE (1 << 3)
#define REF_ARTICLE (1 << 4)
#define REF_AUTHOR (1 << 5)
#define REF_EDITOR (1 << 6)
#define REF_PUBLISHER (1 << 7)
#define REF_ISBN (1 << 8)

    int Mask = 0;

1408 1409 1410 1411 1412 1413 1414 1415 1416
    if(Ref->site)      { Mask |= REF_SITE; }
    if(Ref->page)      { Mask |= REF_PAGE; }
    if(Ref->url)       { Mask |= REF_URL; }
    if(Ref->title)     { Mask |= REF_TITLE; }
    if(Ref->article)   { Mask |= REF_ARTICLE; }
    if(Ref->author)    { Mask |= REF_AUTHOR; }
    if(Ref->editor)    { Mask |= REF_EDITOR; }
    if(Ref->publisher) { Mask |= REF_PUBLISHER; }
    if(Ref->isbn)      { Mask |= REF_ISBN; }
1417 1418

    if((REF_URL | REF_TITLE | REF_AUTHOR | REF_PUBLISHER | REF_ISBN) == Mask)
1419
    {
1420 1421 1422 1423
        CopyString(ReferencesArray[UniqueRefs].ID, Ref->isbn);
        CopyString(ReferencesArray[UniqueRefs].Source, "%s (%s)", Ref->author, Ref->publisher);
        CopyStringNoFormat(ReferencesArray[UniqueRefs].RefTitle, Ref->title);
        CopyStringNoFormat(ReferencesArray[UniqueRefs].URL, Ref->url);
1424
    }
1425 1426
    else if((REF_AUTHOR | REF_SITE | REF_PAGE