#if 0 ctime -begin ${0%.*}.ctm #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 #clang -fsanitize=address -g -Wall -std=c99 -pipe $0 -o ${0%.*} hmml.a -lcurl #clang -O2 -Wall -std=c99 -pipe $0 -o ${0%.*} hmml.a -lcurl ctime -end ${0%.*}.ctm exit #endif typedef struct { unsigned int Major, Minor, Patch; } version; version CINERA_APP_VERSION = { .Major = 0, .Minor = 5, .Patch = 66 }; // TODO(matt): Copy in the DB 3 stuff from cinera_working.c #define CINERA_DB_VERSION 3 #include // NOTE(matt): varargs #include // NOTE(matt): printf, sprintf, vsprintf, fprintf, perror #include // NOTE(matt): calloc, malloc, free #include "hmmlib.h" #include // NOTE(matt): getopts //#include "config.h" // TODO(matt): Implement config.h #include #include #include #include #include #include // NOTE(matt): strerror #include //NOTE(matt): errno #include // NOTE(matt): inotify #include // NOTE(matt): sleep() typedef unsigned int bool; #define TRUE 1 #define FALSE 0 #define DEBUG 0 #define DEBUG_MEM 0 bool PROFILING = 0; clock_t TIMING_START; #define START_TIMING_BLOCK(...) if(PROFILING) { printf(__VA_ARGS__); TIMING_START = clock(); } #define END_TIMING_BLOCK() if(PROFILING) { printf("\e[1;34m%ld\e[0m\n", clock() - TIMING_START);} #define Kilobytes(Bytes) Bytes << 10 #define Megabytes(Bytes) Bytes << 20 #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 #define MAX_CUSTOM_SNIPPET_SHORT_LENGTH 255 #define MAX_CUSTOM_SNIPPET_LONG_LENGTH 1023 enum { EDITION_SINGLE, EDITION_PROJECT, EDITION_NETWORK } editions; 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; enum { MODE_FORCEINTEGRATION = 1 << 0, MODE_ONESHOT = 1 << 1, MODE_EXAMINE = 1 << 2, MODE_NOCACHE = 1 << 3, MODE_NOPRIVACY = 1 << 4, MODE_SINGLETAB = 1 << 5 } modes; enum { RC_ARENA_FULL, RC_ERROR_DIRECTORY, RC_ERROR_FATAL, RC_ERROR_FILE, RC_ERROR_HMML, RC_ERROR_MAX_REFS, RC_ERROR_MEMORY, RC_ERROR_PROJECT, RC_ERROR_QUOTE, RC_ERROR_SEEK, RC_FOUND, RC_UNFOUND, RC_INVALID_REFERENCE, RC_INVALID_TEMPLATE, RC_PRIVATE_VIDEO, RC_NOOP, RC_RIP, RC_SUCCESS } returns; typedef struct { void *Location; void *Ptr; char *ID; int Size; } arena; typedef struct { // Universal char CacheDir[256]; int Edition; int LogLevel; int Mode; int UpdateInterval; // 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 LastPrivacyCheck; time_t LastQuoteFetch; // typedef struct { char *Location; char *Ptr; char *ID; int Size; } buffer; typedef struct { buffer Buffer; FILE *Handle; char Path[256]; // NOTE(matt): Could this just be a char *? int FileSize; } file_buffer; // 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]; // TODO(matt): Replace this with the OutputPath, when we add that } 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! 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; 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]; char ProjectID[MAX_PROJECT_ID_LENGTH + 1]; char ProjectName[MAX_PROJECT_NAME_LENGTH + 1]; char Theme[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]; char VideoID[16]; } buffers; enum { // Contents and Player Pages Mandatory TAG_INCLUDES, // Contents Page Mandatory TAG_INDEX, // Player Page Mandatory TAG_MENUS, TAG_PLAYER, TAG_SCRIPT, // 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, TAG_TITLE, TAG_VIDEO_ID, // Anywhere Optional TAG_PROJECT, TAG_PROJECT_ID, TAG_THEME, TAG_URL, } template_tags; typedef struct { int Code; // template_tags char *Tag; } tag; tag Tags[] = { { TAG_INCLUDES, "__CINERA_INCLUDES__" }, { TAG_INDEX, "__CINERA_INDEX__" }, { TAG_MENUS, "__CINERA_MENUS__" }, { TAG_PLAYER, "__CINERA_PLAYER__" }, { TAG_SCRIPT, "__CINERA_SCRIPT__" }, { 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__" }, { TAG_TITLE, "__CINERA_TITLE__" }, { TAG_VIDEO_ID, "__CINERA_VIDEO_ID__" }, { TAG_PROJECT, "__CINERA_PROJECT__" }, { TAG_PROJECT_ID, "__CINERA_PROJECT_ID__" }, { TAG_THEME, "__CINERA_THEME__" }, { TAG_URL, "__CINERA_URL__" }, }; typedef struct { int Offset; int TagCode; } tag_offset; typedef struct { char Filename[256]; 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; } template_metadata; typedef struct { template_metadata Metadata; buffer Buffer; } template; // 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; typedef struct { char Timecode[8]; int Identifier; } identifier; #define REF_MAX_IDENTIFIER 64 typedef struct { char RefTitle[620]; char ID[512]; char URL[512]; char Source[256]; identifier Identifier[REF_MAX_IDENTIFIER]; int IdentifierCount; } ref_info; typedef struct { char Marker[32]; char WrittenText[32]; } category_info; typedef struct { category_info Category[64]; int Count; } categories; // TODO(matt): Parse this stuff out of a config file typedef struct { char *Username; char *CreditedName; char *HomepageURL; char *SupportIcon; char *SupportURL; } credential_info; credential_info Credentials[] = { { "a_waterman", "Andrew Waterman", "https://www.linkedin.com/in/andrew-waterman-76805788", "", ""}, { "y_lee", "Yunsup Lee", "https://www.linkedin.com/in/yunsup-lee-385b692b/", "", ""}, { "AndrewJDR", "Andrew Johnson", "", "", ""}, { "AsafGartner", "Asaf Gartner", "", "", ""}, { "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", "", ""}, { "Mannilie", "Emmanuel Vaccaro", "http://emmanuelvaccaro.com/", "", ""}, { "Miblo", "Matt Mascarenhas", "https://miblodelcarpio.co.uk/", "cinera_sprite_sendowl.png", "https://miblodelcarpio.co.uk/cinera#pledge"}, { "Mr4thDimention", "Allen Webster", "http://www.4coder.net/", "", ""}, { "Pseudonym73", "Andrew Bromage", "https://twitter.com/deguerre", "", ""}, { "Quel_Solaar", "Eskil Steenberg", "http://quelsolaar.com/", "", ""}, { "ZedZull", "Jay Waggle", "", "", ""}, { "abnercoimbre", "Abner Coimbre", "https://handmade.network/m/abnercoimbre", "", ""}, { "brianwill", "Brian Will", "http://brianwill.net/blog/", "", ""}, { "cbloom", "Charles Bloom", "http://cbloomrants.blogspot.co.uk/", "", ""}, { "cmuratori", "Casey Muratori", "https://handmadehero.org", "cinera_sprite_sendowl.png", "https://handmadehero.org/fund"}, { "csnover", "Colin Snover", "https://zetafleet.com/", "", ""}, { "debiatan", "Miguel Lechón", "http://blog.debiatan.net/", "", ""}, { "dspecht", "Dustin Specht", "", "", ""}, { "effect0r", "Cory Henderlite", "", "", ""}, { "ffsjs", "ffsjs", "", "", ""}, { "fierydrake", "Mike Tunnicliffe", "", "", ""}, { "garlandobloom", "Matthew VanDevander", "https://lowtideproductions.com/", "cinera_sprite_patreon.png", "https://www.patreon.com/mv"}, { "ikerms", "Iker Murga", "", "", ""}, { "insofaras", "Alex Baines", "https://abaines.me.uk/", "", ""}, { "jacebennett", "Jace Bennett", "", "", ""}, { "jon", "Jonathan Blow", "http://the-witness.net/news/", "", ""}, { "jpike", "Jacob Pike", "", "", ""}, { "martincohen", "Martin Cohen", "http://blog.coh.io/", "", ""}, { "miotatsu", "Mio Iwakura", "http://riscy.tv/", "cinera_sprite_patreon.png", "https://patreon.com/miotatsu"}, { "nothings", "Sean Barrett", "https://nothings.org/", "", ""}, { "pervognsen", "Per Vognsen", "https://github.com/pervognsen/bitwise/", "", ""}, { "philipbuuck", "Philip Buuck", "http://philipbuuck.com/", "", ""}, { "powerc9000", "Clay Murray", "http://claymurray.website/", "", ""}, { "rygorous", "Fabian Giesen", "https://fgiesen.wordpress.com/", "", ""}, { "schme", "Kasper Sauramo", "", "", ""}, { "sssmcgrath", "Shawn McGrath", "http://www.dyadgame.com/", "", ""}, { "thehappiecat", "Anne", "https://www.youtube.com/c/TheHappieCat", "cinera_sprite_patreon.png", "https://www.patreon.com/thehappiecat"}, { "theinternetftw", "Ben Craddock", "", "", ""}, { "wheatdog", "Tim Liou", "http://stringbulbs.com/", "", ""}, { "williamchyr", "William Chyr", "http://williamchyr.com/", "", ""}, { "wonchun", "Won Chun", "https://twitter.com/won3d", "", ""}, }; typedef struct { char *Medium; char *Icon; char *WrittenName; } category_medium; category_medium CategoryMedium[] = { // medium icon written name { "admin", "🗹", "Administrivia"}, { "afk", "…" , "Away from Keyboard"}, { "authored", "🗪", "Chat Comment"}, // TODO(matt): Conditionally handle Chat vs Guest Comments { "blackboard", "🖌", "Blackboard"}, { "drawing", "🎨", "Drawing"}, { "experience", "🍷", "Experience"}, { "hat", "🎩", "Hat"}, { "multimedia", "🎬", "Media Clip"}, { "owl", "🦉", "Owl of Shame"}, { "programming", "🖮", "Programming"}, // TODO(matt): Potentially make this configurable per project { "rant", "💢", "Rant"}, { "research", "📖", "Research"}, { "run", "🏃", "In-Game"}, // TODO(matt): Potentially make this configurable per project { "speech", "🗩", "Speech"}, { "trivia", "🎲", "Trivia"}, }; enum { NS_CALENDRICAL, NS_LINEAR, NS_SEASONAL, } numbering_schemes; typedef struct { char *ProjectID; char *FullName; char *Unit; // e.g. Day, Episode, Session int NumberingScheme; // numbering_schemes char *Medium; char *AltURLPrefix; // NOTE(matt): This currently just straight up replaces the ProjectID in the player pages' output directories } project_info; project_info ProjectInfo[] = { { "bitwise", "Bitwise", "Day", NS_LINEAR, "programming", "" }, { "book", "Book Club", "Day", NS_LINEAR, "research", "" }, { "coad", "Computer Organization and Design", "", NS_LINEAR, "research", "" }, { "reader", "RISC-V Reader", "", NS_LINEAR, "research", "" }, { "riscy", "RISCY BUSINESS", "Day", NS_LINEAR, "programming", "" }, { "risc", "RISCellaneous", "", NS_CALENDRICAL, "speech", "" }, { "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", "" }, { "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", "" }, { "obbg", "Open Block Building Game", "Episode", NS_LINEAR, "programming", "" }, { "sysadmin", "SysAdmin", "Session", NS_LINEAR, "admin", "" }, }; #define ArrayCount(A) sizeof(A)/sizeof(*(A)) void Clear(char *String, int Size) { for(int i = 0; i < Size; ++i) { String[i] = 0; } } int StringLength(char *String) { int i = 0; while(String[i]) { ++i; } return i; } #define CopyString(Dest, DestSize, Format, ...) CopyString_(__LINE__, (Dest), (DestSize), (Format), ##__VA_ARGS__) __attribute__ ((format (printf, 4, 5))) int CopyString_(int LineNumber, char Dest[], int DestSize, char *Format, ...) { int Length = 0; va_list Args; va_start(Args, Format); Length = vsnprintf(Dest, DestSize, Format, Args); if(Length >= DestSize) { printf("CopyString() call on line %d has been passed a buffer too small (%d bytes) to contain null-terminated %d(+1)-character string\n", LineNumber, DestSize, Length); __asm__("int3"); } va_end(Args); return Length; } #define CopyStringNoFormat(Dest, DestSize, String) CopyStringNoFormat_(__LINE__, Dest, DestSize, String) int CopyStringNoFormat_(int LineNumber, char *Dest, int DestSize, char *String) { int Length = 0; char *Start = String; while(*String) { *Dest++ = *String++; ++Length; } if(Length >= DestSize) { printf("CopyStringNoFormat() call on line %d has been passed a buffer too small (%d bytes) to contain null-terminated %d(+1)-character string:\n" "%s\n", LineNumber, DestSize, Length, Start); __asm__("int3"); } *Dest = '\0'; return Length; } #define ClearCopyStringNoFormat(Dest, DestSize, String) ClearCopyStringNoFormat_(__LINE__, Dest, DestSize, String) int ClearCopyStringNoFormat_(int LineNumber, char *Dest, int DestSize, char *String) { Clear(Dest, DestSize); int Length = 0; char *Start = String; while(*String) { *Dest++ = *String++; ++Length; } if(Length >= DestSize) { printf("ClearCopyStringNoFormat() call on line %d has been passed a buffer too small (%d bytes) to contain null-terminated %d(+1)-character string:\n" "%s\n", LineNumber, DestSize, Length, Start); __asm__("int3"); } *Dest = '\0'; return Length; } // TODO(matt): Maybe do a version of this that takes a string as a Terminator #define CopyStringNoFormatT(Dest, DestSize, String, Terminator) CopyStringNoFormatT_(__LINE__, Dest, DestSize, String, Terminator) int CopyStringNoFormatT_(int LineNumber, char *Dest, int DestSize, char *String, char Terminator) { int Length = 0; char *Start = String; while(*String != Terminator) { *Dest++ = *String++; ++Length; } if(Length >= DestSize) { printf("CopyStringNoFormatT() call on line %d has been passed a buffer too small (%d bytes) to contain %c-terminated %d(+1)-character string:\n" "%.*s\n", LineNumber, DestSize, Terminator == 0 ? '0' : Terminator, Length, Length, Start); __asm__("int3"); } *Dest = '\0'; return Length; } #define CopyStringToBuffer(Dest, Format, ...) CopyStringToBuffer_(__LINE__, Dest, Format, ##__VA_ARGS__) __attribute__ ((format (printf, 3, 4))) void CopyStringToBuffer_(int LineNumber, buffer *Dest, char *Format, ...) { va_list Args; va_start(Args, Format); int Length = vsnprintf(Dest->Ptr, Dest->Size - (Dest->Ptr - Dest->Location), Format, Args); va_end(Args); if(Length + (Dest->Ptr - Dest->Location) >= Dest->Size) { fprintf(stderr, "CopyStringToBuffer(%s) call on line %d cannot accommodate null-terminated %d(+1)-character string:\n" "%s\n", Dest->ID, LineNumber, Length, Format); __asm__("int3"); } Dest->Ptr += Length; } #define CopyStringToBufferNoFormat(Dest, String) CopyStringToBufferNoFormat_(__LINE__, Dest, String) void CopyStringToBufferNoFormat_(int LineNumber, buffer *Dest, char *String) { char *Start = String; while(*String) { *Dest->Ptr++ = *String++; } if(Dest->Ptr - Dest->Location >= Dest->Size) { fprintf(stderr, "CopyStringToBufferNoFormat(%s) call on line %d cannot accommodate %d-character string:\n" "%s\n", Dest->ID, LineNumber, StringLength(Start), Start); __asm__("int3"); } *Dest->Ptr = '\0'; } #define CopyStringToBufferHTMLSafe(Dest, String) CopyStringToBufferHTMLSafe_(__LINE__, Dest, String) void CopyStringToBufferHTMLSafe_(int LineNumber, buffer *Dest, char *String) { char *Start = String; int Length = StringLength(String); while(*String) { switch(*String) { case '<': *Dest->Ptr++ = '&'; *Dest->Ptr++ = 'l'; *Dest->Ptr++ = 't'; *Dest->Ptr++ = ';'; Length += 3; break; case '>': *Dest->Ptr++ = '&'; *Dest->Ptr++ = 'g'; *Dest->Ptr++ = 't'; *Dest->Ptr++ = ';'; Length += 3; break; case '&': *Dest->Ptr++ = '&'; *Dest->Ptr++ = 'a'; *Dest->Ptr++ = 'm'; *Dest->Ptr++ = 'p'; *Dest->Ptr++ = ';'; Length += 4; break; case '\"': *Dest->Ptr++ = '&'; *Dest->Ptr++ = 'q'; *Dest->Ptr++ = 'u'; *Dest->Ptr++ = 'o'; *Dest->Ptr++ = 't'; *Dest->Ptr++ = ';'; Length += 5; break; case '\'': *Dest->Ptr++ = '&'; *Dest->Ptr++ = '#'; *Dest->Ptr++ = '3'; *Dest->Ptr++ = '9'; *Dest->Ptr++ = ';'; Length += 4; break; default: *Dest->Ptr++ = *String; break; } ++String; } if(Dest->Ptr - Dest->Location >= Dest->Size) { fprintf(stderr, "CopyStringToBufferHTMLSafe(%s) call on line %d cannot accommodate %d(+1)-character HTML-sanitised string:\n" "%s\n", Dest->ID, LineNumber, Length, Start); __asm__("int3"); } *Dest->Ptr = '\0'; } #define CopyStringToBufferHTMLSafeBreakingOnSlash(Dest, String) CopyStringToBufferHTMLSafeBreakingOnSlash_(__LINE__, Dest, String) void CopyStringToBufferHTMLSafeBreakingOnSlash_(int LineNumber, buffer *Dest, char *String) { char *Start = String; int Length = StringLength(String); while(*String) { switch(*String) { case '<': *Dest->Ptr++ = '&'; *Dest->Ptr++ = 'l'; *Dest->Ptr++ = 't'; *Dest->Ptr++ = ';'; Length += 3; break; case '>': *Dest->Ptr++ = '&'; *Dest->Ptr++ = 'g'; *Dest->Ptr++ = 't'; *Dest->Ptr++ = ';'; Length += 3; break; case '&': *Dest->Ptr++ = '&'; *Dest->Ptr++ = 'a'; *Dest->Ptr++ = 'm'; *Dest->Ptr++ = 'p'; *Dest->Ptr++ = ';'; Length += 4; break; case '\'': *Dest->Ptr++ = '&'; *Dest->Ptr++ = '#'; *Dest->Ptr++ = '3'; *Dest->Ptr++ = '9'; *Dest->Ptr++ = ';'; Length += 4; break; case '\"': *Dest->Ptr++ = '&'; *Dest->Ptr++ = 'q'; *Dest->Ptr++ = 'u'; *Dest->Ptr++ = 'o'; *Dest->Ptr++ = 't'; *Dest->Ptr++ = ';'; Length += 5; break; case '/': *Dest->Ptr++ = '/'; *Dest->Ptr++ = '&'; *Dest->Ptr++ = '#'; *Dest->Ptr++ = '8'; *Dest->Ptr++ = '2'; *Dest->Ptr++ = '0'; *Dest->Ptr++ = '3'; *Dest->Ptr++ = ';'; Length += 7; break; default: *Dest->Ptr++ = *String; break; } ++String; } if(Dest->Ptr - Dest->Location >= Dest->Size) { fprintf(stderr, "CopyStringToBufferHTMLSafeBreakingOnSlash_(%s) call on line %d cannot accommodate %d(+1)-character HTML-sanitised string:\n" "%s\n", Dest->ID, LineNumber, Length, Start); __asm__("int3"); } } #define CopyBuffer(Dest, Src) CopyBuffer_(__LINE__, Dest, Src) void CopyBuffer_(int LineNumber, buffer *Dest, buffer *Src) { Src->Ptr = Src->Location; while(*Src->Ptr) { *Dest->Ptr++ = *Src->Ptr++; } if(Dest->Ptr - Dest->Location >= Dest->Size) { fprintf(stderr, "CopyBuffer(%s) call on line %d cannot accommodate %d(+1)-character %s\n", Dest->ID, LineNumber, StringLength(Src->Location), Src->ID); __asm__("int3"); } *Dest->Ptr = '\0'; } #define CopyBufferSized(Dest, Src, Size) CopyBufferSized_(__LINE__, Dest, Src, Size) void CopyBufferSized_(int LineNumber, buffer *Dest, buffer *Src, int Size) { Src->Ptr = Src->Location; while(Src->Ptr - Src->Location < Size) { *Dest->Ptr++ = *Src->Ptr++; } if(Dest->Ptr - Dest->Location >= Dest->Size) { fprintf(stderr, "CopyBufferNoNull(%s) call on line %d cannot accommodate %d(+1)-character %s\n", Dest->ID, LineNumber, StringLength(Src->Location), Src->ID); __asm__("int3"); } } int StringsDiffer(char *A, char *B) // NOTE(matt): Two null-terminated strings { while(*A && *B && *A == *B) { ++A, ++B; } return *A - *B; } int StringsDifferCaseInsensitive(char *A, char *B) // NOTE(matt): Two null-terminated strings { while(*A && *B && ((*A >= 'A' && *A <= 'Z') ? *A + ('a' - 'A') : *A) == ((*B >= 'A' && *B <= 'Z') ? *B + ('a' - 'A') : *B)) { ++A, ++B; } return *A - *B; } bool StringsDifferT(char *A, // NOTE(matt): Null-terminated string char *B, // NOTE(matt): Not null-terminated string (e.g. one mid-buffer) char Terminator // NOTE(matt): Caller definable terminator. Pass 0 to only match on the extent of A ) { // TODO(matt): Make sure this can't crash upon reaching the end of B's buffer int ALength = StringLength(A); int i = 0; while(i < ALength && A[i] && A[i] == B[i]) { ++i; } if((!Terminator && !A[i] && ALength == i) || (!A[i] && ALength == i && (B[i] == Terminator))) { return FALSE; } else { return TRUE; } } int MakeDir(char *Path) { // TODO(matt): Correctly check for permissions int i = StringLength(Path); int Ancestors = 0; while(mkdir(Path, 00755) == -1) { if(errno == EACCES) { return RC_ERROR_DIRECTORY; } while(Path[i] != '/' && i > 0) { --i; } ++Ancestors; Path[i] = '\0'; if(i == 0) { return RC_ERROR_DIRECTORY; } } while(Ancestors > 0) { while(Path[i] != '\0') { ++i; } Path[i] = '/'; --Ancestors; if((mkdir(Path, 00755)) == -1) { return RC_ERROR_DIRECTORY; } } return RC_SUCCESS; } void LogUsage(buffer *Buffer) { #if DEBUG char LogPath[256]; CopyString(LogPath, "%s/%s", Config.CacheDir, "buffers.log"); FILE *LogFile; if(!(LogFile = fopen(LogPath, "a+"))) { MakeDir(Config.CacheDir); if(!(LogFile = fopen(LogPath, "a+"))) { perror("LogUsage"); return; } } fprintf(LogFile, "%s,%ld,%d\n", Buffer->ID, Buffer->Ptr - Buffer->Location, Buffer->Size); fclose(LogFile); #endif } __attribute__ ((format (printf, 2, 3))) void LogError(int LogLevel, char *Format, ...) { if(Config.LogLevel >= LogLevel) { char LogPath[256]; CopyString(LogPath, sizeof(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); } } void FreeBuffer(buffer *Buffer) { free(Buffer->Location); Buffer->Location = 0; #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 } #if 0 #define ClaimBuffer(MemoryArena, Buffer, ID, Size) if(__ClaimBuffer(MemoryArena, Buffer, ID, Size))\ {\ fprintf(stderr, "%s:%d: MemoryArena cannot contain %s of size %d\n", __FILE__, __LINE__, ID, Size);\ hmml_free(&HMML);\ FreeBuffer(MemoryArena);\ return 1;\ }; #endif int ClaimBuffer(buffer *Buffer, char *ID, int Size) { if(MemoryArena.Ptr - MemoryArena.Location + Size > MemoryArena.Size) { return RC_ARENA_FULL; } Buffer->Location = (char *)MemoryArena.Ptr; Buffer->Size = Size; Buffer->ID = ID; MemoryArena.Ptr += Buffer->Size; *Buffer->Location = '\0'; Buffer->Ptr = Buffer->Location; #if DEBUG float PercentageUsed = (float)(MemoryArena.Ptr - MemoryArena.Location) / MemoryArena.Size * 100; printf(" ClaimBuffer(%s): %d\n" " Total ClaimedMemory: %ld (%.2f%%, leaving %ld free)\n\n", Buffer->ID, Buffer->Size, MemoryArena.Ptr - MemoryArena.Location, PercentageUsed, MemoryArena.Size - (MemoryArena.Ptr - MemoryArena.Location)); #endif return RC_SUCCESS; } void DeclaimBuffer(buffer *Buffer) { *Buffer->Location = '\0'; MemoryArena.Ptr -= Buffer->Size; float PercentageUsed = (float)(Buffer->Ptr - Buffer->Location) / Buffer->Size * 100; #if DEBUG printf("DeclaimBuffer(%s)\n" " Used: %ld / %d (%.2f%%)\n" "\n" " Total ClaimedMemory: %ld\n\n", Buffer->ID, Buffer->Ptr - Buffer->Location, Buffer->Size, PercentageUsed, MemoryArena.Ptr - MemoryArena.Location); #endif LogUsage(Buffer); if(PercentageUsed >= 95.0f) { // TODO(matt): Implement either dynamically growing buffers, or phoning home to matt@handmadedev.org LogError(LOG_ERROR, "%s used %.2f%% of its allotted memory\n", Buffer->ID, PercentageUsed); fprintf(stderr, "\e[1;31mWarning\e[0m: %s used %.2f%% of its allotted memory\n", Buffer->ID, PercentageUsed); } else if(PercentageUsed >= 80.0f) { // TODO(matt): Implement either dynamically growing buffers, or phoning home to matt@handmadedev.org LogError(LOG_ERROR, "%s used %.2f%% of its allotted memory\n", Buffer->ID, PercentageUsed); fprintf(stderr, "\e[0;33mWarning\e[0m: %s used %.2f%% of its allotted memory\n", Buffer->ID, PercentageUsed); } Buffer->Size = 0; } 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; } enum { TEMPLATE_INDEX, TEMPLATE_PLAYER, TEMPLATE_BESPOKE } templates; 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; } void ConstructTemplatePath(template *Template, int TemplateType) { // NOTE(matt): Bespoke template paths are set relative to: // in Project Edition: ProjectDir // in Single Edition: Parent directory of .hmml file if(Template->Metadata.Filename[0] != '/') { char Temp[256]; CopyString(Temp, sizeof(Temp), "%s", Template->Metadata.Filename); char *Ptr = Template->Metadata.Filename; char *End = Template->Metadata.Filename + sizeof(Template->Metadata.Filename); if(TemplateType == TEMPLATE_BESPOKE) { if(Config.Edition == EDITION_SINGLE) { Ptr += CopyString(Ptr, End - Ptr, "%s/", GetDirectoryPath(Config.SingleHMMLFilePath)); } else { Ptr += CopyString(Ptr, End - Ptr, "%s/", Config.ProjectDir); } } else { Ptr += CopyString(Ptr, End - Ptr, "%s/", Config.TemplatesDir); } CopyString(Ptr, End - Ptr, "%s", Temp); } } int InitTemplate(template **Template) { if(MemoryArena.Ptr - MemoryArena.Location + sizeof(template) > MemoryArena.Size) { return RC_ARENA_FULL; } *Template = (template *)MemoryArena.Ptr; 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] { (*Template)->Metadata.Tag[i].Offset = 0; (*Template)->Metadata.Tag[i].TagCode = 0; } MemoryArena.Ptr += sizeof(template); return RC_SUCCESS; } int ClaimTemplate(template **Template, char *Location, int TemplateType) { CopyString((*Template)->Metadata.Filename, sizeof((*Template)->Metadata.Filename), "%s", Location); ConstructTemplatePath((*Template), TemplateType); if(TemplateType == TEMPLATE_BESPOKE) { fprintf(stderr, "\e[0;35mPacking\e[0m template: %s\n", (*Template)->Metadata.Filename); } 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)); Clear((*Template)->Metadata.Filename, 256); // NOTE(matt): template_metadata specifies Filename[256] return RC_ERROR_FILE; } fseek(File, 0, SEEK_END); (*Template)->Buffer.Size = ftell(File); if(MemoryArena.Ptr - MemoryArena.Location + (*Template)->Buffer.Size > MemoryArena.Size) { Clear((*Template)->Metadata.Filename, 256); // NOTE(matt): template_metadata specifies Filename[256] return RC_ARENA_FULL; } (*Template)->Buffer.Location = MemoryArena.Ptr; (*Template)->Buffer.Ptr = (*Template)->Buffer.Location; (*Template)->Buffer.ID = (*Template)->Metadata.Filename; fseek(File, 0, SEEK_SET); fread((*Template)->Buffer.Location, (*Template)->Buffer.Size, 1, File); fclose(File); MemoryArena.Ptr += (*Template)->Buffer.Size; #if DEBUG printf(" ClaimTemplate(%s): %d\n" " Total ClaimedMemory: %ld\n\n", (*Template)->Metadata.Filename, (*Template)->Buffer.Size, MemoryArena.Ptr - MemoryArena.Location); #endif return RC_SUCCESS; } int DeclaimTemplate(template *Template) { 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; #if DEBUG printf("DeclaimTemplate(%s)\n" " Total ClaimedMemory: %ld\n\n", (*Template).Metadata.Filename, MemoryArena.Ptr - MemoryArena.Location); #endif return RC_SUCCESS; } 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]; } typedef struct { unsigned int Hue:16; unsigned int Saturation:8; unsigned int Lightness:8; } hsl_colour; hsl_colour CharToColour(char Char) { hsl_colour Colour; if(Char >= 'a' && Char <= 'z') { Colour.Hue = (((float)Char - 'a') / ('z' - 'a') * 360); Colour.Saturation = (((float)Char - 'a') / ('z' - 'a') * 26 + 74); } else if(Char >= 'A' && Char <= 'Z') { Colour.Hue = (((float)Char - 'A') / ('Z' - 'A') * 360); Colour.Saturation = (((float)Char - 'A') / ('Z' - 'A') * 26 + 74); } else if(Char >= '0' && Char <= '9') { Colour.Hue = (((float)Char - '0') / ('9' - '0') * 360); Colour.Saturation = (((float)Char - '0') / ('9' - '0') * 26 + 74); } else { Colour.Hue = 180; Colour.Saturation = 50; } return Colour; } void StringToColourHash(hsl_colour *Colour, char *String) { Colour->Hue = 0; Colour->Saturation = 0; Colour->Lightness = 74; int i; for(i = 0; String[i]; ++i) { Colour->Hue += CharToColour(String[i]).Hue; Colour->Saturation += CharToColour(String[i]).Saturation; } Colour->Hue = Colour->Hue % 360; Colour->Saturation = Colour->Saturation % 26 + 74; } char * SanitisePunctuation(char *String) { char *Ptr = String; while(*Ptr) { if(*Ptr == ' ') { *Ptr = '_'; } if((*Ptr < '0' || *Ptr > '9') && (*Ptr < 'a' || *Ptr > 'z') && (*Ptr < 'A' || *Ptr > 'Z')) { *Ptr = '-'; } ++Ptr; } return String; } 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) { RewindBuffer(URLPrefix); if(StringsDiffer(Config.RootURL, "")) { CopyStringToBuffer(URLPrefix, "%s/", Config.RootURL); } else { if(Config.Edition == EDITION_PROJECT) { if(PageType == PAGE_PLAYER) { CopyStringToBuffer(URLPrefix, "../"); } CopyStringToBuffer(URLPrefix, "../"); } } switch(IncludeType) { case INCLUDE_CSS: if(StringsDiffer(Config.CSSDir, "")) { CopyStringToBuffer(URLPrefix, "%s/", Config.CSSDir); } break; case INCLUDE_Images: if(StringsDiffer(Config.ImagesDir, "")) { CopyStringToBuffer(URLPrefix, "%s/", Config.ImagesDir); } break; case INCLUDE_JS: if(StringsDiffer(Config.JSDir, "")) { CopyStringToBuffer(URLPrefix, "%s/", Config.JSDir); } break; } } typedef struct { char Abbreviation[32]; hsl_colour Colour; credential_info *Credential; bool Seen; } speaker; typedef struct { speaker Speaker[16]; int Count; } speakers; enum { CreditsError_NoHost, CreditsError_NoAnnotator, CreditsError_NoCredentials } credits_errors; int SearchCredentials(buffer *CreditsMenu, bool *HasCreditsMenu, char *Person, char *Role, speakers *Speakers) { bool Found = FALSE; for(int CredentialIndex = 0; CredentialIndex < ArrayCount(Credentials); ++CredentialIndex) { if(!StringsDiffer(Person, Credentials[CredentialIndex].Username)) { if(Speakers) { Speakers->Speaker[Speakers->Count].Credential = &Credentials[CredentialIndex]; ++Speakers->Count; } Found = TRUE; if(*HasCreditsMenu == FALSE) { CopyStringToBuffer(CreditsMenu, "
\n" " Credits\n" "
\n"); *HasCreditsMenu = TRUE; } CopyStringToBuffer(CreditsMenu, " \n"); if(*Credentials[CredentialIndex].HomepageURL) { CopyStringToBuffer(CreditsMenu, " \n" "
%s
\n" "
%s
\n" "
\n", Credentials[CredentialIndex].HomepageURL, Role, Credentials[CredentialIndex].CreditedName); } else { CopyStringToBuffer(CreditsMenu, "
\n" "
%s
\n" "
%s
\n" "
\n", Role, Credentials[CredentialIndex].CreditedName); } if(*Credentials[CredentialIndex].SupportIcon && *Credentials[CredentialIndex].SupportURL) { buffer URLPrefix; ClaimBuffer(&URLPrefix, "URLPrefix", 1024); ConstructURLPrefix(&URLPrefix, INCLUDE_Images, PAGE_PLAYER); CopyStringToBuffer(CreditsMenu, "
\n", Credentials[CredentialIndex].SupportURL, URLPrefix.Location, Credentials[CredentialIndex].SupportIcon); DeclaimBuffer(&URLPrefix); } CopyStringToBuffer(CreditsMenu, "
\n"); } } return Found ? RC_SUCCESS : CreditsError_NoCredentials; } void ClearNullTerminatedString(char *String) { while(*String) { *String++ = '\0'; } } void InitialString(char *Dest, char *Src) { ClearNullTerminatedString(Dest); *Dest++ = *Src++; while(*Src++) { if(*Src == ' ') { ++Src; if(*Src) { *Dest++ = *Src; } } } } void GetFirstSubstring(char *Dest, char *Src) { ClearNullTerminatedString(Dest); while(*Src && *Src != ' ') { *Dest++ = *Src++; } } void InitialAndGetFinalString(char *Dest, int DestSize, char *Src) { ClearNullTerminatedString(Dest); int SrcLength = StringLength(Src); char *SrcPtr = Src + SrcLength - 1; while(SrcPtr > Src && *SrcPtr != ' ') { --SrcPtr; } if(*SrcPtr == ' ' && SrcPtr - Src < SrcLength - 1) { ++SrcPtr; } if(Src < SrcPtr) { *Dest++ = *Src++; *Dest++ = '.'; *Dest++ = ' '; while(Src < SrcPtr - 1) { if(*Src == ' ') { ++Src; if(*Src) { *Dest++ = *Src; *Dest++ = '.'; *Dest++ = ' '; } } ++Src; } } CopyString(Dest, DestSize, "%s", SrcPtr); } bool AbbreviationsClash(speakers *Speakers) { for(int i = 0; i < Speakers->Count; ++i) { for(int j = i + 1; j < Speakers->Count; ++j) { if(!StringsDiffer(Speakers->Speaker[i].Abbreviation, Speakers->Speaker[j].Abbreviation)) { return TRUE; } } } return FALSE; } void SortAndAbbreviateSpeakers(speakers *Speakers) { for(int i = 0; i < Speakers->Count; ++i) { for(int j = i + 1; j < Speakers->Count; ++j) { if(StringsDiffer(Speakers->Speaker[i].Credential->Username, Speakers->Speaker[j].Credential->Username) > 0) { credential_info *Temp = Speakers->Speaker[j].Credential; Speakers->Speaker[j].Credential = Speakers->Speaker[i].Credential; Speakers->Speaker[i].Credential = Temp; break; } } } for(int i = 0; i < Speakers->Count; ++i) { StringToColourHash(&Speakers->Speaker[i].Colour, Speakers->Speaker[i].Credential->Username); InitialString(Speakers->Speaker[i].Abbreviation, Speakers->Speaker[i].Credential->CreditedName); } int Attempt = 0; while(AbbreviationsClash(Speakers)) { for(int i = 0; i < Speakers->Count; ++i) { switch(Attempt) { case 0: GetFirstSubstring(Speakers->Speaker[i].Abbreviation, Speakers->Speaker[i].Credential->CreditedName); break; case 1: InitialAndGetFinalString(Speakers->Speaker[i].Abbreviation, sizeof(Speakers->Speaker[i].Abbreviation), Speakers->Speaker[i].Credential->CreditedName); break; case 2: ClearCopyStringNoFormat(Speakers->Speaker[i].Abbreviation, sizeof(Speakers->Speaker[i].Abbreviation), Speakers->Speaker[i].Credential->Username); break; } } ++Attempt; } } int BuildCredits(buffer *CreditsMenu, bool *HasCreditsMenu, HMML_VideoMetaData *Metadata, speakers *Speakers) // TODO(matt): Make this take the Credentials, once we are parsing them from a config { if(SearchCredentials(CreditsMenu, HasCreditsMenu, Metadata->member, "Host", Speakers) == CreditsError_NoCredentials) { printf("No credentials for member %s. Please contact matt@handmadedev.org with their:\n" " Full name\n" " Homepage URL (optional)\n" " Financial support info, e.g. Patreon URL (optional)\n", Metadata->member); return CreditsError_NoCredentials; } if(Metadata->co_host_count > 0) { for(int i = 0; i < Metadata->co_host_count; ++i) { if(SearchCredentials(CreditsMenu, HasCreditsMenu, Metadata->co_hosts[i], "Co-host", Speakers) == CreditsError_NoCredentials) { printf("No credentials for co-host %s. Please contact matt@handmadedev.org with their:\n" " Full name\n" " Homepage URL (optional)\n" " Financial support info, e.g. Patreon URL (optional)\n", Metadata->co_hosts[i]); return CreditsError_NoCredentials; } } } if(Metadata->guest_count > 0) { for(int i = 0; i < Metadata->guest_count; ++i) { if(SearchCredentials(CreditsMenu, HasCreditsMenu, Metadata->guests[i], "Guest", Speakers) == CreditsError_NoCredentials) { printf("No credentials for guest %s. Please contact matt@handmadedev.org with their:\n" " Full name\n" " Homepage URL (optional)\n" " Financial support info, e.g. Patreon URL (optional)\n", Metadata->guests[i]); return CreditsError_NoCredentials; } } } if(Speakers->Count > 1) { SortAndAbbreviateSpeakers(Speakers); } if(Metadata->annotator_count > 0) { for(int i = 0; i < Metadata->annotator_count; ++i) { if(SearchCredentials(CreditsMenu, HasCreditsMenu, Metadata->annotators[i], "Annotator", 0) == CreditsError_NoCredentials) { printf("No credentials for annotator %s. Please contact matt@handmadedev.org with their:\n" " Full name\n" " Homepage URL (optional)\n" " Financial support info, e.g. Patreon URL (optional)\n", Metadata->annotators[i]); return CreditsError_NoCredentials; } } } else { if(*HasCreditsMenu == TRUE) { CopyStringToBuffer(CreditsMenu, "
\n" "
\n"); } fprintf(stderr, "Missing \"annotator\" in the [video] node\n"); return CreditsError_NoAnnotator; } if(*HasCreditsMenu == TRUE) { CopyStringToBuffer(CreditsMenu, " \n" " \n"); } return RC_SUCCESS; } enum { REF_SITE = 1 << 0, REF_PAGE = 1 << 1, REF_URL = 1 << 2, REF_TITLE = 1 << 3, REF_ARTICLE = 1 << 4, REF_AUTHOR = 1 << 5, REF_EDITOR = 1 << 6, REF_PUBLISHER = 1 << 7, REF_ISBN = 1 << 8, } reference_fields; int BuildReference(ref_info *ReferencesArray, int RefIdentifier, int UniqueRefs, HMML_Reference *Ref, HMML_Annotation *Anno) { if(Ref->isbn) { CopyString(ReferencesArray[UniqueRefs].ID, sizeof(ReferencesArray[UniqueRefs].ID), "%s", Ref->isbn); if(!Ref->url) { CopyString(ReferencesArray[UniqueRefs].URL, sizeof(ReferencesArray[UniqueRefs].URL), "https://isbndb.com/book/%s", Ref->isbn); } else { CopyStringNoFormat(ReferencesArray[UniqueRefs].URL, sizeof(ReferencesArray[UniqueRefs].URL), Ref->url); } } else if(Ref->url) { CopyStringNoFormat(ReferencesArray[UniqueRefs].ID, sizeof(ReferencesArray[UniqueRefs].ID), Ref->url); CopyStringNoFormat(ReferencesArray[UniqueRefs].URL, sizeof(ReferencesArray[UniqueRefs].URL), Ref->url); } else { return RC_INVALID_REFERENCE; } int Mask = 0; if(Ref->site) { Mask |= REF_SITE; } if(Ref->page) { Mask |= REF_PAGE; } 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; } // TODO(matt): Consider handling the various combinations more flexibly, unless we defer this stuff until we have the // reference store, in which we could optionally customise the display of each reference entry switch(Mask) { case (REF_TITLE | REF_AUTHOR | REF_PUBLISHER): { CopyString(ReferencesArray[UniqueRefs].Source, sizeof(ReferencesArray[UniqueRefs].Source), "%s (%s)", Ref->author, Ref->publisher); CopyStringNoFormat(ReferencesArray[UniqueRefs].RefTitle, sizeof(ReferencesArray[UniqueRefs].RefTitle), Ref->title); } break; case (REF_AUTHOR | REF_SITE | REF_PAGE): { CopyStringNoFormat(ReferencesArray[UniqueRefs].Source, sizeof(ReferencesArray[UniqueRefs].Source), Ref->site); CopyString(ReferencesArray[UniqueRefs].RefTitle, sizeof(ReferencesArray[UniqueRefs].RefTitle), "%s: \"%s\"", Ref->author, Ref->page); } break; case (REF_PAGE | REF_TITLE): { CopyStringNoFormat(ReferencesArray[UniqueRefs].Source, sizeof(ReferencesArray[UniqueRefs].Source), Ref->title); CopyStringNoFormat(ReferencesArray[UniqueRefs].RefTitle, sizeof(ReferencesArray[UniqueRefs].RefTitle), Ref->page); } break; case (REF_SITE | REF_PAGE): { CopyStringNoFormat(ReferencesArray[UniqueRefs].Source, sizeof(ReferencesArray[UniqueRefs].Source), Ref->site); CopyStringNoFormat(ReferencesArray[UniqueRefs].RefTitle, sizeof(ReferencesArray[UniqueRefs].RefTitle), Ref->page); } break; case (REF_SITE | REF_TITLE): { CopyStringNoFormat(ReferencesArray[UniqueRefs].Source, sizeof(ReferencesArray[UniqueRefs].Source), Ref->site); CopyStringNoFormat(ReferencesArray[UniqueRefs].RefTitle, sizeof(ReferencesArray[UniqueRefs].RefTitle), Ref->title); } break; case (REF_TITLE | REF_AUTHOR): { CopyStringNoFormat(ReferencesArray[UniqueRefs].Source, sizeof(ReferencesArray[UniqueRefs].Source), Ref->author); CopyStringNoFormat(ReferencesArray[UniqueRefs].RefTitle, sizeof(ReferencesArray[UniqueRefs].RefTitle), Ref->title); } break; case (REF_ARTICLE | REF_AUTHOR): { CopyStringNoFormat(ReferencesArray[UniqueRefs].Source, sizeof(ReferencesArray[UniqueRefs].Source), Ref->author); CopyStringNoFormat(ReferencesArray[UniqueRefs].RefTitle, sizeof(ReferencesArray[UniqueRefs].RefTitle), Ref->article); } break; case (REF_TITLE | REF_PUBLISHER): { CopyStringNoFormat(ReferencesArray[UniqueRefs].Source, sizeof(ReferencesArray[UniqueRefs].Source), Ref->publisher); CopyStringNoFormat(ReferencesArray[UniqueRefs].RefTitle, sizeof(ReferencesArray[UniqueRefs].RefTitle), Ref->title); } break; case REF_TITLE: { CopyStringNoFormat(ReferencesArray[UniqueRefs].RefTitle, sizeof(ReferencesArray[UniqueRefs].RefTitle), Ref->title); } break; case REF_SITE: { CopyStringNoFormat(ReferencesArray[UniqueRefs].RefTitle, sizeof(ReferencesArray[UniqueRefs].RefTitle), Ref->site); } break; default: return RC_INVALID_REFERENCE; break; } CopyString(ReferencesArray[UniqueRefs].Identifier[ReferencesArray[UniqueRefs].IdentifierCount].Timecode, sizeof(ReferencesArray[UniqueRefs].Identifier[ReferencesArray[UniqueRefs].IdentifierCount].Timecode), "%s", Anno->time); ReferencesArray[UniqueRefs].Identifier[ReferencesArray[UniqueRefs].IdentifierCount].Identifier = RefIdentifier; return RC_SUCCESS; } void InsertCategory(categories *GlobalTopics, categories *LocalTopics, categories *GlobalMedia, categories *LocalMedia, char *Marker) { bool IsMedium = FALSE; int CategoryMediumIndex; for(CategoryMediumIndex = 0; CategoryMediumIndex < ArrayCount(CategoryMedium); ++CategoryMediumIndex) { if(!StringsDiffer(CategoryMedium[CategoryMediumIndex].Medium, Marker)) { IsMedium = TRUE; break; } } if(IsMedium) { int MediumIndex; for(MediumIndex = 0; MediumIndex < LocalMedia->Count; ++MediumIndex) { if(!StringsDiffer(CategoryMedium[CategoryMediumIndex].Medium, LocalMedia->Category[MediumIndex].Marker)) { return; } if((StringsDiffer(CategoryMedium[CategoryMediumIndex].WrittenName, LocalMedia->Category[MediumIndex].WrittenText)) < 0) { int CategoryCount; for(CategoryCount = LocalMedia->Count; CategoryCount > MediumIndex; --CategoryCount) { CopyString(LocalMedia->Category[CategoryCount].Marker, sizeof(LocalMedia->Category[CategoryCount].Marker), "%s", LocalMedia->Category[CategoryCount-1].Marker); CopyString(LocalMedia->Category[CategoryCount].WrittenText, sizeof(LocalMedia->Category[CategoryCount].WrittenText), "%s", LocalMedia->Category[CategoryCount-1].WrittenText); } CopyString(LocalMedia->Category[CategoryCount].Marker, sizeof(LocalMedia->Category[CategoryCount].Marker), "%s", CategoryMedium[CategoryMediumIndex].Medium); CopyString(LocalMedia->Category[CategoryCount].WrittenText, sizeof(LocalMedia->Category[CategoryCount].WrittenText), "%s", CategoryMedium[CategoryMediumIndex].WrittenName); break; } } if(MediumIndex == LocalMedia->Count) { CopyString(LocalMedia->Category[MediumIndex].Marker, sizeof(LocalMedia->Category[MediumIndex].Marker), "%s", CategoryMedium[CategoryMediumIndex].Medium); CopyString(LocalMedia->Category[MediumIndex].WrittenText, sizeof(LocalMedia->Category[MediumIndex].WrittenText), "%s", CategoryMedium[CategoryMediumIndex].WrittenName); } ++LocalMedia->Count; for(MediumIndex = 0; MediumIndex < GlobalMedia->Count; ++MediumIndex) { if(!StringsDiffer(CategoryMedium[CategoryMediumIndex].Medium, GlobalMedia->Category[MediumIndex].Marker)) { return; } if((StringsDiffer(CategoryMedium[CategoryMediumIndex].WrittenName, GlobalMedia->Category[MediumIndex].WrittenText)) < 0) { int CategoryCount; for(CategoryCount = GlobalMedia->Count; CategoryCount > MediumIndex; --CategoryCount) { CopyString(GlobalMedia->Category[CategoryCount].Marker, sizeof(GlobalMedia->Category[CategoryCount].Marker), "%s", GlobalMedia->Category[CategoryCount-1].Marker); CopyString(GlobalMedia->Category[CategoryCount].WrittenText, sizeof(GlobalMedia->Category[CategoryCount].WrittenText), "%s", GlobalMedia->Category[CategoryCount-1].WrittenText); } CopyString(GlobalMedia->Category[CategoryCount].Marker, sizeof(GlobalMedia->Category[CategoryCount].Marker), "%s", CategoryMedium[CategoryMediumIndex].Medium); CopyString(GlobalMedia->Category[CategoryCount].WrittenText, sizeof(GlobalMedia->Category[CategoryCount].WrittenText), "%s", CategoryMedium[CategoryMediumIndex].WrittenName); break; } } if(MediumIndex == GlobalMedia->Count) { CopyString(GlobalMedia->Category[MediumIndex].Marker, sizeof(GlobalMedia->Category[MediumIndex].Marker), "%s", CategoryMedium[CategoryMediumIndex].Medium); CopyString(GlobalMedia->Category[MediumIndex].WrittenText, sizeof(GlobalMedia->Category[MediumIndex].WrittenText), "%s", CategoryMedium[CategoryMediumIndex].WrittenName); } ++GlobalMedia->Count; } else { int TopicIndex; for(TopicIndex = 0; TopicIndex < LocalTopics->Count; ++TopicIndex) { if(!StringsDiffer(Marker, LocalTopics->Category[TopicIndex].Marker)) { return; } if((StringsDiffer(Marker, LocalTopics->Category[TopicIndex].Marker)) < 0) { int CategoryCount; for(CategoryCount = LocalTopics->Count; CategoryCount > TopicIndex; --CategoryCount) { CopyString(LocalTopics->Category[CategoryCount].Marker, sizeof(LocalTopics->Category[CategoryCount].Marker), "%s", LocalTopics->Category[CategoryCount-1].Marker); } CopyString(LocalTopics->Category[CategoryCount].Marker, sizeof(LocalTopics->Category[CategoryCount].Marker), "%s", Marker); break; } } if(TopicIndex == LocalTopics->Count) { CopyString(LocalTopics->Category[TopicIndex].Marker, sizeof(LocalTopics->Category[TopicIndex].Marker), "%s", Marker); } ++LocalTopics->Count; for(TopicIndex = 0; TopicIndex < GlobalTopics->Count; ++TopicIndex) { if(!StringsDiffer(Marker, GlobalTopics->Category[TopicIndex].Marker)) { return; } // NOTE(matt): This successfully sorts "nullTopic" at the end, but maybe figure out a more general way to force the // order of stuff, perhaps blocks of dudes that should sort to the start / end if(((StringsDiffer(Marker, GlobalTopics->Category[TopicIndex].Marker)) < 0 || !StringsDiffer(GlobalTopics->Category[TopicIndex].Marker, "nullTopic"))) { if(StringsDiffer(Marker, "nullTopic")) // NOTE(matt): This test (with the above || condition) forces nullTopic never to be inserted, only appended { int CategoryCount; for(CategoryCount = GlobalTopics->Count; CategoryCount > TopicIndex; --CategoryCount) { CopyString(GlobalTopics->Category[CategoryCount].Marker, sizeof(GlobalTopics->Category[CategoryCount].Marker), "%s", GlobalTopics->Category[CategoryCount-1].Marker); } CopyString(GlobalTopics->Category[CategoryCount].Marker, sizeof(GlobalTopics->Category[CategoryCount].Marker), "%s", Marker); break; } } } if(TopicIndex == GlobalTopics->Count) { CopyString(GlobalTopics->Category[TopicIndex].Marker, sizeof(GlobalTopics->Category[TopicIndex].Marker), "%s", Marker); } ++GlobalTopics->Count; } } void BuildCategories(buffer *AnnotationClass, buffer *CategoryIcons, categories *LocalTopics, categories *LocalMedia, int *MarkerIndex, char *DefaultMedium) { bool CategoriesSpan = FALSE; if(!(LocalTopics->Count == 1 && !StringsDiffer(LocalTopics->Category[0].Marker, "nullTopic") && LocalMedia->Count == 1 && !StringsDiffer(LocalMedia->Category[0].Marker, DefaultMedium))) { CategoriesSpan = TRUE; CopyStringToBuffer(CategoryIcons, ""); } if(LocalTopics->Count == 1 && !StringsDiffer(LocalTopics->Category[0].Marker, "nullTopic")) { char SanitisedMarker[StringLength(LocalTopics->Category[0].Marker) + 1]; CopyString(SanitisedMarker, sizeof(SanitisedMarker), "%s", LocalTopics->Category[0].Marker); SanitisePunctuation(SanitisedMarker); CopyStringToBuffer(AnnotationClass, " cat_%s", SanitisedMarker); } else { for(int i = 0; i < LocalTopics->Count; ++i) { char SanitisedMarker[StringLength(LocalTopics->Category[i].Marker) + 1]; CopyString(SanitisedMarker, sizeof(SanitisedMarker), "%s", LocalTopics->Category[i].Marker); SanitisePunctuation(SanitisedMarker); CopyStringToBuffer(CategoryIcons, "
", LocalTopics->Category[i].Marker, SanitisedMarker); CopyStringToBuffer(AnnotationClass, " cat_%s", SanitisedMarker); } } if(LocalMedia->Count == 1 && !StringsDiffer(LocalMedia->Category[0].Marker, DefaultMedium)) { char SanitisedMarker[StringLength(LocalMedia->Category[0].Marker) + 1]; CopyString(SanitisedMarker, sizeof(SanitisedMarker), "%s", LocalMedia->Category[0].Marker); SanitisePunctuation(SanitisedMarker); CopyStringToBuffer(AnnotationClass, " %s", SanitisedMarker); } else { for(int i = 0; i < LocalMedia->Count; ++i) { char SanitisedMarker[StringLength(LocalMedia->Category[i].Marker) + 1]; CopyString(SanitisedMarker, sizeof(SanitisedMarker), "%s", LocalMedia->Category[i].Marker); SanitisePunctuation(SanitisedMarker); if(!StringsDiffer(LocalMedia->Category[i].Marker, "afk")) // TODO(matt): Initially hidden config { CopyStringToBuffer(AnnotationClass, " off_%s skip", SanitisedMarker); // TODO(matt): Bulletproof this? } else { for(int j = 0; j < ArrayCount(CategoryMedium); ++j) { if(!StringsDiffer(LocalMedia->Category[i].Marker, CategoryMedium[j].Medium)) { CopyStringToBuffer(CategoryIcons, "
%s
", LocalMedia->Category[i].WrittenText, LocalMedia->Category[i].Marker, CategoryMedium[j].Icon); CopyStringToBuffer(AnnotationClass, " %s", SanitisedMarker); } } } } } if(CategoriesSpan) { CopyStringToBuffer(CategoryIcons, "
"); } CopyStringToBuffer(AnnotationClass, "\""); } int StringToInt(char *String) { int Result = 0; while(*String) { Result = Result * 10 + (*String - '0'); ++String; } return Result; } size_t CurlIntoBuffer(char *InPtr, size_t CharLength, size_t Chars, char **OutputPtr) { int Length = CharLength * Chars; int i; for(i = 0; InPtr[i] && i < Length; ++i) { *((*OutputPtr)++) = InPtr[i]; } **OutputPtr = '\0'; return Length; }; void CurlQuotes(buffer *QuoteStaging, char *QuotesURL) { fprintf(stderr, "\e[0;35mFetching\e[0m quotes: %s\n", QuotesURL); CURL *curl = curl_easy_init(); if(curl) { CURLcode CurlReturnCode; curl_easy_setopt(curl, CURLOPT_WRITEDATA, &QuoteStaging->Ptr); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlIntoBuffer); curl_easy_setopt(curl, CURLOPT_URL, QuotesURL); if((CurlReturnCode = curl_easy_perform(curl))) { fprintf(stderr, "%s\n", curl_easy_strerror(CurlReturnCode)); } curl_easy_cleanup(curl); } } int SearchQuotes(buffer *QuoteStaging, int CacheSize, quote_info *Info, int ID) { QuoteStaging->Ptr = QuoteStaging->Location; while(QuoteStaging->Ptr - QuoteStaging->Location < CacheSize) { char InID[8] = { 0 }; char InTime[16] = { 0 }; QuoteStaging->Ptr += CopyStringNoFormatT(InID, sizeof(InID), QuoteStaging->Ptr, ',') + 1; // Skip past the ',' if(StringToInt(InID) == ID) { QuoteStaging->Ptr += CopyStringNoFormatT(InTime, sizeof(InTime), QuoteStaging->Ptr, ',') + 1; // Skip past the ',' long int Time = StringToInt(InTime); char DayString[3] = { 0 }; strftime(DayString, 3, "%d", gmtime(&Time)); int Day = StringToInt(DayString); char DaySuffix[3]; if(DayString[1] == '1' && Day != 11) { CopyString(DaySuffix, sizeof(DaySuffix), "st"); } else if(DayString[1] == '2' && Day != 12) { CopyString(DaySuffix, sizeof(DaySuffix), "nd"); } else if(DayString[1] == '3' && Day != 13) { CopyString(DaySuffix, sizeof(DaySuffix), "rd"); } else { CopyString(DaySuffix, sizeof(DaySuffix), "th"); } char MonthYear[32]; strftime(MonthYear, 32, "%B, %Y", gmtime(&Time)); CopyString(Info->Date, sizeof(Info->Date), "%d%s %s", Day, DaySuffix, MonthYear); CopyStringNoFormatT(Info->Text, sizeof(Info->Text), QuoteStaging->Ptr, '\n'); FreeBuffer(QuoteStaging); return RC_FOUND; } else { while(*QuoteStaging->Ptr != '\n') { ++QuoteStaging->Ptr; } ++QuoteStaging->Ptr; } } return RC_UNFOUND; } int BuildQuote(quote_info *Info, char *Speaker, int ID, bool ShouldFetchQuotes) { char QuoteCacheDir[256]; CopyString(QuoteCacheDir, sizeof(QuoteCacheDir), "%s/quotes", Config.CacheDir); char QuoteCachePath[256]; CopyString(QuoteCachePath, sizeof(QuoteCachePath), "%s/%s", QuoteCacheDir, Speaker); FILE *QuoteCache; char QuotesURL[256]; // TODO(matt): Make the URL configurable and also handle the case in which the .raw isn't available CopyString(QuotesURL, sizeof(QuotesURL), "https://dev.abaines.me.uk/quotes/%s.raw", Speaker); bool CacheAvailable = FALSE; if(!(QuoteCache = fopen(QuoteCachePath, "a+"))) { if(MakeDir(QuoteCacheDir) == RC_SUCCESS) { CacheAvailable = TRUE; } if(!(QuoteCache = fopen(QuoteCachePath, "a+"))) { fprintf(stderr, "Unable to open quote cache %s: %s\n", QuoteCachePath, strerror(errno)); } else { CacheAvailable = TRUE; } } else { CacheAvailable = TRUE; } buffer QuoteStaging; QuoteStaging.ID = "QuoteStaging"; QuoteStaging.Size = Kilobytes(256); if(!(QuoteStaging.Location = malloc(QuoteStaging.Size))) { fclose(QuoteCache); return RC_ERROR_MEMORY; } #if DEBUG_MEM FILE *MemLog = fopen("/home/matt/cinera_mem", "a+"); fprintf(MemLog, " Allocated QuoteStaging (%d)\n", QuoteStaging.Size); fclose(MemLog); printf(" Allocated QuoteStaging (%d)\n", QuoteStaging.Size); #endif QuoteStaging.Ptr = QuoteStaging.Location; if(CacheAvailable) { fseek(QuoteCache, 0, SEEK_END); int FileSize = ftell(QuoteCache); fseek(QuoteCache, 0, SEEK_SET); fread(QuoteStaging.Location, FileSize, 1, QuoteCache); fclose(QuoteCache); if(ShouldFetchQuotes || SearchQuotes(&QuoteStaging, FileSize, Info, ID) == RC_UNFOUND) { CurlQuotes(&QuoteStaging, QuotesURL); if(!(QuoteCache = fopen(QuoteCachePath, "w"))) { perror(QuoteCachePath); } fwrite(QuoteStaging.Location, QuoteStaging.Ptr - QuoteStaging.Location, 1, QuoteCache); fclose(QuoteCache); int CacheSize = QuoteStaging.Ptr - QuoteStaging.Location; QuoteStaging.Ptr = QuoteStaging.Location; if(SearchQuotes(&QuoteStaging, CacheSize, Info, ID) == RC_UNFOUND) { FreeBuffer(&QuoteStaging); return RC_UNFOUND; } } } else { CurlQuotes(&QuoteStaging, QuotesURL); int CacheSize = QuoteStaging.Ptr - QuoteStaging.Location; QuoteStaging.Ptr = QuoteStaging.Location; if(SearchQuotes(&QuoteStaging, CacheSize, Info, ID) == RC_UNFOUND) { FreeBuffer(&QuoteStaging); return RC_UNFOUND; } } return RC_SUCCESS; } int GenerateTopicColours(char *Topic) { char SanitisedTopic[StringLength(Topic) + 1]; CopyString(SanitisedTopic, sizeof(SanitisedTopic), "%s", Topic); SanitisePunctuation(SanitisedTopic); for(int i = 0; i < ArrayCount(CategoryMedium); ++i) { if(!StringsDiffer(Topic, CategoryMedium[i].Medium)) { return RC_NOOP; } } file_buffer Topics; Topics.Buffer.ID = "Topics"; if(StringsDiffer(Config.CSSDir, "")) { CopyString(Topics.Path, sizeof(Topics.Path), "%s/%s/cinera_topics.css", Config.RootDir, Config.CSSDir); } else { CopyString(Topics.Path, sizeof(Topics.Path), "%s/cinera_topics.css", Config.RootDir); } char *Ptr = Topics.Path + StringLength(Topics.Path) - 1; while(*Ptr != '/') { --Ptr; } *Ptr = '\0'; DIR *CSSDirHandle; // TODO(matt): open() if(!(CSSDirHandle = opendir(Topics.Path))) { if(MakeDir(Topics.Path) == RC_ERROR_DIRECTORY) { LogError(LOG_ERROR, "Unable to create directory %s: %s", Topics.Path, strerror(errno)); fprintf(stderr, "Unable to create directory %s: %s\n", Topics.Path, strerror(errno)); return RC_ERROR_DIRECTORY; }; } closedir(CSSDirHandle); *Ptr = '/'; if((Topics.Handle = fopen(Topics.Path, "a+"))) { fseek(Topics.Handle, 0, SEEK_END); Topics.FileSize = ftell(Topics.Handle); Topics.Buffer.Size = Topics.FileSize; fseek(Topics.Handle, 0, SEEK_SET); if(!(Topics.Buffer.Location = malloc(Topics.Buffer.Size))) { return RC_ERROR_MEMORY; } #if DEBUG_MEM FILE *MemLog = fopen("/home/matt/cinera_mem", "a+"); fprintf(MemLog, " Allocated Topics (%d)\n", Topics.Buffer.Size); fclose(MemLog); printf(" Allocated Topics (%d)\n", Topics.Buffer.Size); #endif Topics.Buffer.Ptr = Topics.Buffer.Location; fread(Topics.Buffer.Location, Topics.Buffer.Size, 1, Topics.Handle); while(Topics.Buffer.Ptr - Topics.Buffer.Location < Topics.Buffer.Size) { Topics.Buffer.Ptr += StringLength(".category."); if(!StringsDifferT(SanitisedTopic, Topics.Buffer.Ptr, ' ')) { FreeBuffer(&Topics.Buffer); fclose(Topics.Handle); return RC_NOOP; } while(Topics.Buffer.Ptr - Topics.Buffer.Location < Topics.Buffer.Size && *Topics.Buffer.Ptr != '\n') { ++Topics.Buffer.Ptr; } ++Topics.Buffer.Ptr; } if(!StringsDiffer(Topic, "nullTopic")) { fprintf(Topics.Handle, ".category.%s { border: 1px solid transparent; background: transparent; }\n", SanitisedTopic); } else { hsl_colour Colour; StringToColourHash(&Colour, Topic); fprintf(Topics.Handle, ".category.%s { border: 1px solid hsl(%d, %d%%, %d%%); background: hsl(%d, %d%%, %d%%); }\n", SanitisedTopic, Colour.Hue, Colour.Saturation, Colour.Lightness, Colour.Hue, Colour.Saturation, Colour.Lightness); } fclose(Topics.Handle); FreeBuffer(&Topics.Buffer); return RC_SUCCESS; } else { // NOTE(matt): Maybe it shouldn't be possible to hit this case now that we MakeDir the actually dir... perror(Topics.Path); return RC_ERROR_FILE; } } void PrintUsage(char *BinaryLocation, config *DefaultConfig) { fprintf(stderr, "Usage: %s [option(s)] filename(s)\n" "\n" "Options:\n" " Paths: \e[1;30m(advisedly universal, but may be set per-(sub)project as required)\e[0m\n" " -r \n" " Override default root directory (\"%s\")\n" " -R \n" " Override default root URL (\"%s\")\n" " \e[1;31mIMPORTANT\e[0m: -r and -R must correspond to the same location\n" " \e[1;30mUNSUPPORTED: If you move files from RootDir, the RootURL should\n" " correspond to the resulting location\e[0m\n" "\n" " -c \n" " Override default CSS directory (\"%s\"), relative to root\n" " -i \n" " Override default images directory (\"%s\"), relative to root\n" " -j \n" " Override default JS directory (\"%s\"), relative to root\n" "\n" " Project Settings:\n" " -p \n" " Set the project ID, equal to the \"project\" field in the HMML files\n" " NOTE: Setting the project ID triggers PROJECT EDITION\n" " -m \n" " Override default default medium (\"%s\")\n" " \e[1;30mKnown project defaults:\n", BinaryLocation, DefaultConfig->RootDir, DefaultConfig->RootURL, DefaultConfig->CSSDir, DefaultConfig->ImagesDir, DefaultConfig->JSDir, DefaultConfig->DefaultMedium); for(int ProjectIndex = 0; ProjectIndex < ArrayCount(ProjectInfo); ++ProjectIndex) { fprintf(stderr, " %s:", ProjectInfo[ProjectIndex].ProjectID); // NOTE(matt): This kind of thing really needs to loop over the dudes once to find the longest one for(int i = 11; i > StringLength(ProjectInfo[ProjectIndex].ProjectID); i -= 4) { fprintf(stderr, "\t"); } fprintf(stderr, "%s\n", ProjectInfo[ProjectIndex].Medium); } fprintf(stderr, "\e[0m -s