From a11acb0fa8cdefed186638235ed96964077f27c1 Mon Sep 17 00:00:00 2001 From: Laurent Cozic Date: Sun, 2 Jul 2017 19:38:34 +0100 Subject: [PATCH] sync tags --- CliClient/app/fuzzing.js | 15 +++-- CliClient/app/import-enex.js | 16 +++--- CliClient/app/main.js | 4 +- CliClient/tests/test-utils.js | 1 - lib/base-model.js | 6 +- lib/database.js | 11 +--- lib/models/base-item.js | 34 +++++++++--- lib/models/change.js | 101 ---------------------------------- lib/models/folder.js | 4 -- lib/models/note.js | 4 -- lib/models/tag.js | 47 ++++++++++++++-- lib/synchronizer.js | 5 ++ 12 files changed, 92 insertions(+), 156 deletions(-) delete mode 100644 lib/models/change.js diff --git a/CliClient/app/fuzzing.js b/CliClient/app/fuzzing.js index ee603f836..ce23a016d 100644 --- a/CliClient/app/fuzzing.js +++ b/CliClient/app/fuzzing.js @@ -49,7 +49,7 @@ function randomElement(array) { } function randomWord() { - const words = ['belief','scandalous','flawless','wrestle','sort','moldy','carve','incompetent','cruel','awful','fang','holistic','makeshift','synonymous','questionable','soft','drop','boot','whimsical','stir','idea','adhesive','present','hilarious','unusual','divergent','probable','depend','suck','belong','advise','straight','encouraging','wing','clam','serve','fill','nostalgic','dysfunctional','aggressive','floor','baby','grease','sisters','print','switch','control','victorious','cracker','dream','wistful','adaptable','reminiscent','inquisitive','pushy','unaccountable','receive','guttural','two','protect','skin','unbiased','plastic','loutish','zip','used','divide','communicate','dear','muddled','dinosaurs','grip','trees','well-off','calendar','chickens','irate','deranged','trip','stream','white','poison','attack','obtain','theory','laborer','omniscient','brake','maniacal','curvy','smoke','babies','punch','hammer','toothbrush','same','crown','jagged','peep','difficult','reject','merciful','useless','doctor','mix','wicked','plant','quickest','roll','suffer','curly','brother','frighten','cold','tremendous','move','knot','lame','imaginary','capricious','raspy','aunt','loving','wink','wooden','hop','free','drab','fire','instrument','border','frame','silent','glue','decorate','distance','powerful','pig','admit','fix','pour','flesh','profuse','skinny','learn','filthy','dress','bloody','produce','innocent','meaty','pray','slimy','sun','kindhearted','dime','exclusive','boast','neat','ruthless','recess','grieving','daily','hateful','ignorant','fence','spring','slim','education','overflow','plastic','gaping','chew','detect','right','lunch','gainful','argue','cloistered','horses','orange','shame','bitter','able','sail','magical','exist','force','wheel','best','suit','spurious','partner','request','dog','gusty','money','gaze','lonely','company','pale','tempt','rat','flame','wobble','superficial','stop','protective','stare','tongue','heal','railway','idiotic','roll','puffy','turn','meeting','new','frightening','sophisticated','poke','elderly','room','stimulating','increase','moor','secret','lean','occur','country','damp','evanescent','alluring','oafish','join','thundering','cars','awesome','advice','unruly','ray','wind','anxious','fly','hammer','adventurous','shop','cook','trucks','nonchalant','addition','base','abashed','excuse','giants','dramatic','piquant','coach','possess','poor','finger','wide-eyed','aquatic','welcome','instruct','expert','evasive','hug','cute','return','mice','damage','turkey','quiet','bewildered','tidy','pointless','outrageous','medical','foolish','curve','grandiose','gullible','hapless','gleaming','third','grin','pipe','egg','act','physical','eager','side','milk','tearful','fertile','average','glamorous','strange','yak','terrific','thin','near','snails','flowery','authority','fish','curious','perpetual','healthy','health','match','fade','chemical','economic','drawer','avoid','lying','minister','lick','powder','decay','desire','furry','faint','beam','sordid','fax','tail','bawdy','cherry','letter','clover','ladybug','teeth','behavior','black','amazing','pink','waste','island','forgetful','needless','lock','waves','boundary','receipt','handy','religion','hypnotic','aftermath','explain','sense','mundane','rambunctious','second','preserve','alarm','dusty','event','blow','weigh','value','glorious','jail','sigh','cemetery','serious','yummy','cattle','understood','limit','alert','fear','lucky','tested','surround','dolls','pleasant','disillusioned','discover','tray','night','seemly','liquid','worry','pen','bent','gruesome','war','teeny-tiny','common','judge','symptomatic','bed','trot','unequaled','flowers','friends','damaged','peel','skip','show','twist','worthless','brush','look','behave','imperfect','week','petite','direction','soda','lively','coal','coil','release','berserk','books','impossible','replace','cough','chunky','torpid','discreet','material','bomb','soothe','crack','hope','license','frightened','breathe','maddening','calculator','committee','paltry','green','subsequent','arrest','gigantic','tasty','metal','willing','man','stem','nonstop','route','impulse','government','comfortable','include','literate','multiply','test','vast','exercise','addicted','agreeable','lace','toes','young','water','end','wash','glossy','round','staking','sink','open','spot','trip','fierce','robust','pastoral','drown','dress','machine','calculating','holiday','crabby','disgusting','plan','sleet','sleepy','typical','borrow','possible','curtain','airplane','industry','nut','rough','wacky','rock','enormous','uninterested','sugar','rake','consist','wrist','basket','chop','wet','street','known','settle','bless','cluttered','wild','expand','angle','snake','yawn','hate','flood','rabid','spiteful','anger','market','bizarre','force','majestic','scissors','beg','rifle','foregoing','cactus','funny','eggnog','wish','high-pitched','drop','camp','scarf','car','groan','wonderful','wealthy','cup','lock','available','previous','jam','political','vacation','three','desk','fry','aspiring','productive','clear','bored','flashy','plug','precede','abhorrent','muddle','flimsy','paste','need','reward','frail','obnoxious','creature','whip','unbecoming','lake','unused','chin','tour','zephyr','experience','building','scrub','correct','hover','panicky','scorch','diligent','hulking','ubiquitous','tedious','aberrant','file','accidental','mist','blue-eyed','trite','nondescript','cows','wait','test','snotty','amuck','jump','lackadaisical','grey','tawdry','strong','land','kind','star','ludicrous','stupid','telling','use','bruise','whirl','cream','harsh','aboriginal','substantial','brawny','tease','pollution','weather','degree','dry','film','obey','closed','dependent','want','undesirable','stamp','relax','foot','obscene','successful','wriggle','drain','greasy','escape','cross','odd','boring','absorbed','houses','suppose','suit','moon','ceaseless','explode','clap','pop','courageous','miss','notebook','delirious','form','pretty','sock','grotesque','noxious','record','stop','saw','thing','dislike','cloth','six','jar','unnatural','spiffy','itchy','secretary','move','certain','unkempt','sassy','queue','shrug','crow','heavenly','desert','screw','vessel','mug','encourage','icy','enthusiastic','throat','whistle','ignore','miniature','squeak','scarecrow','fluttering','hang','icicle','lie','juicy','empty','baseball','various','promise','abortive','descriptive','high','spy','faded','talk','air','mess up','decorous','sneaky','mark','sack','ultra','chivalrous','lethal','expect','disgusted','reaction','fireman','private','ritzy','manage','actor','rely','uppity','thread','bat','space','underwear','blood','nine','maid','shelf','hanging','shop','prick','wound','sloppy','offer','increase','clear','slap','rude','poised','wretched','cause','quince','tame','remarkable','abject','sail','guide','subdued','spiky','debonair','chicken','tired','hum','land','scared','splendid','guess','cast','rub','magnificent','ants','overwrought','interfere','gorgeous','office','trade','sniff','melted','bore','point','pet','purple','brake','flavor','toe','prickly','zinc','homely','modern','kindly','whisper','bare','annoyed','glass','noisy','null','thoughtless','skirt','dock','rings','mind','neck','macho','wave','history','play','road','profit','word','opposite','dreary','governor','horse','trust','elbow','kiss','crayon','stitch','excited','needy','arrange','easy','alcoholic','safe','lumpy','monkey','smile','capable','untidy','extra-small','memory','selective','reproduce','old-fashioned','overrated','texture','knit','downtown','risk','pot','sofa','righteous','wren','pull','carry','aboard','listen','classy','thank','shocking','condition','root','attempt','swim','frog','hurt','army','title','handsomely','town','guiltless','thaw','spell','selfish','disturbed','tramp','girls','utopian','noiseless','trail','bashful','business','rhetorical','snail','sign','plausible','left','design','tall','violent','wasteful','beautiful','breezy','tap','murder','talented','needle','creator','imagine','flippant','dead','bone','coherent','relation','aromatic','mountainous','face','ask','picture','pedal','colour','obese','group','top','bubble','pinch','optimal','school','bathe','flagrant','check','deliver','pass','tan','crate','hose','debt','faulty','longing','hollow','invincible','afford','lovely','ticket','changeable','subtract','fumbling','responsible','confused','woman','touch','watch','zesty','library','jail','wrap','terrify','brick','popcorn','cooperative','peck','pocket','property','buzz','tiresome','digestion','exciting','nation','juvenile','shade','copper','wanting','deer','waste','man','join','spotty','amused','mountain','waggish','bushes','tense','river','heartbreaking','help','mine','narrow','smash','scrawny','tame','rain','playground','airport','astonishing','level','befitting','animal','heat','painful','cellar','ski','sedate','knowing','vigorous','change','eight','ship','work','strip','robin','tank','challenge','vacuous','representative','regret','tightfisted','erratic','club','imported','therapeutic','rainstorm','luxuriant','relieved','day','system','apologise','male','prepare','malicious','naive','whistle','curl','hobbies','trousers','stereotyped','dad','endurable','grass','hot','bomb','morning','guide','keen','plot','accept','disastrous','macabre','year','spicy','absorbing','sticks','efficient','drain','warm','rice','utter','fact','marked','ratty','chalk','towering','treat','nest','annoy','jealous','stamp','effect','cautious','jelly','feigned','gabby','corn','volleyball','pan','psychedelic','fairies','silent','zonked','bump','trouble','mass','queen','things','bury','sister','quiet','colossal','puncture','four','attend','love','wiry','vegetable','destruction','note','pies','resolute','load','fancy','tacky','periodic','abandoned','vivacious','blush','wrathful','miscreant','call','striped','wiggly','supreme','hand','impolite','rule','deserted','concern','cover','harbor','waiting','soggy','psychotic','ancient','sponge','domineering','elegant','impartial','unlock','abrasive','count','flight','neighborly','roof','bulb','auspicious','automatic','magic','sign','amusing','orange','branch','sulky','attack','fetch','number','jellyfish','start','alike','touch','sour','wary','minor','punish','connect','protest','pie','kaput','doubtful','friendly','simplistic','smart','vanish','applaud','jumbled','ready','yell','support','squash','raise','parallel','super','jazzy','crush','apathetic','water','food','thrill','permit','heady','last','mine','signal','smoke','preach','x-ray','name','birth','minute','steel','bedroom','female','acrid','riddle','attractive','earth','crack','muscle','alive','guarded','sweater','donkey','doubt','lettuce','magenta','live','farm','glib','bow','fascinated','friend','practise','remember','bleach','hungry','voiceless','pin','sparkling','report','arm','sad','shaggy','parcel','wail','flash','territory','functional','wise','screeching','appliance','future','appear','team','rabbit','porter','paint','flat','amusement','ocean','head','geese','wash','embarrassed','tub','boundless','freezing','mushy','surprise','temporary','marble','recondite','telephone','zipper','pine','reign','pump','tangy','reply','toys','purpose','songs','form','delicious','wood','horn','nutty','fruit','lumber','potato','cheat','cloudy','visit','reduce','destroy','deafening','full','warlike','mitten','cover','earthy','seashore','yarn','tenuous','pause','boil','dogs','tough','knife','shy','naughty','existence','fire','eminent','remove','juice','sleep','voyage','balance','unsightly','plough','ill-fated','pumped','motionless','allow','trade','warm','toad','wave','wall','pigs','circle','rejoice','ear','drink','found','taboo','object','old','temper','plant','public','picayune','blot','delight','carpenter','dispensable','tire','cow','furniture','rightful','mute','gentle','gifted','ragged','stiff','retire','compare','sable','hole','judicious','chilly','sparkle','futuristic','love','bubble','travel','name','numberless','succeed','acoustic','lowly','society','injure','agree','reason','party','wool','careful','hook','bell','ball','attach','scream','development','happy','appreciate','disagree','request','march','rampant','scrape','sack','hair','measure','owe','grubby','vein','boy','punishment','smoggy','wry','immense','shoe','pack','brash','cave','sincere','adorable','fantastic','attraction','racial','jittery','defiant','honey','paper','weight','bee','blind','birthday','toothsome','trick','guard','fog','handle','dirty','salt','rinse','nippy','observe','suggestion','weak','instinctive','frequent','detail','verse','quirky','scattered','toy','aware','distribution','repulsive','draconian','bucket','harm','radiate','bang','shrill','living','rhythm','obsequious','drum','inject','skate','beds','smash','order','stitch','ground','nosy','kick','dusty','home','rot','frame','jam','sky','soap','rescue','energetic','grape','massive','deeply','dazzling','park','pull','number','abundant','barbarous','drag','ajar','close','moan','haircut','shade','married','cats','thirsty','dirt','vagabond','fearful','squealing','squalid','zebra','murky','sheet','fat','follow','bikes','unpack','materialistic','surprise','arch','selection','acoustics','helpless','thoughtful','cry','quarrelsome','arrogant','illegal','sudden','elite','tomatoes','spoil','flower','shivering','front','caption','volcano','ugliest','ambitious','pickle','interrupt','nervous','approve','messy','dust','oceanic','brass','tremble','fine','nerve','lunchroom','hard','engine','erect','flower','cynical','irritating','tight','cobweb','gray','invention','snatch','account','sharp','spooky','squeamish','eatable','share','need','moaning','suspect','rush','rural','false','float','bite','careless','sidewalk','cowardly','stroke','educated','ugly','type','wandering','bolt','mint','fit','large','extra-large','defeated','kitty','tacit','abiding','grandfather','trains','lamp','habitual','fast','offbeat','accurate','many','fortunate','lyrical','charge','illustrious','transport','wakeful','cable','ordinary','string','question','train','fancy','kick','enchanting','jobless','ahead','comparison','loose','dance','add','wonder','stale','earn','reflective','bright','true','statuesque','amount','matter','repair','care','ruin','terrible','elastic','spiders','craven','lamentable','decision','swing','connection','gaudy','knowledge','cheap','lazy','step','dinner','rod','agreement','comb','mean','past','knotty','busy','quicksand','match','early','long','onerous','ambiguous','worried','spade','happen','crook','dapper','grate','announce','plate','haunt','friction','actually','chance','example','rapid','zealous','necessary','ink','mere','shock','huge','jaded','spill','store','fuzzy','table','bottle','halting','spark','end','remain','transport','seat','leg','long-term','clip','grumpy','shake','walk','try','action','soup','short','hurry','square','belligerent','thankful','beginner','small','bumpy','silly','badge','marvelous','wealth','open','unequal','scatter','pest','fool','step','groovy','childlike','door','bouncy','believe','incredible','box','unhealthy','swanky','abrupt','depressed','flaky','famous','detailed','regret','envious','natural','apparel','spare','mark','ten','power','glistening','arrive','animated','slip','heap','shaky','unfasten','contain','inexpensive','introduce','shallow','rule','gather','pump','humorous','acceptable','womanly','giddy','silk','yoke','straw','invite','one','red','growth','unadvised','measly','flap','puzzled','regular','painstaking','little','plain','tumble','rest','fabulous','melt','label','truculent','internal','passenger','zippy','bright','earsplitting','tooth','veil','grip','square','stuff','gate','level','stone','observation','time','workable','bird','realise','spotted','coast','quiver','rebel','entertain','rotten','loss','collect','meal','satisfy','military','bake','cagey','redundant','treatment','knock','blink','scale','board','fair','nebulous','sip','homeless','place','complain','joke','bat','winter','choke','frantic','chubby','highfalutin','troubled','whole','rose','delightful','loaf','afraid','sturdy','class','cultured','yielding','broken','kittens','absurd','discovery','next','disarm','dangerous','lively','reflect','chief','teeny','pencil','ban','grade','size','dashing','thought','breath','empty','hellish','shock','sea','weary','payment','limping','premium','grateful','somber','tax','coach','vulgar','stretch','tow','branch','insurance','yam','stormy','wish','snow','cute','milky','battle','far','roasted','slip','adamant','awake','employ','tangible','tickle','jog','hysterical','meddle','parsimonious','judge','educate','respect','sound','oven','gratis','station','train','purring','steady','carriage','humdrum','voracious','jolly','brainy','proud','elfin','cure','motion','record','quizzical','pail','bike','faithful','approval','vague','fall','store','normal','rock','bear','bounce','giant','satisfying','crooked','lopsided','vest','separate','sneeze','teaching','general','meat','festive','historical','line','north','tip','son','damaging','nimble','broad','list','confuse','first','deserve','steep','last','rich','oval','thick','glow','great','clammy','cheer','untidy','scientific','noise','stomach','undress','big','bite-sized','enter','cake','aloof','abnormal','month','grab','well-groomed','silver','art','berry','giraffe','complete','billowy','thumb','squeal','crib','discussion','even','stretch','mellow','angry','grouchy','absent','snow','middle','stingy','mourn','deep','honorable','nice','verdant','reach','lavish','sin','interest','whine','tug','vengeful','rhyme','stay','upset','hesitant','tent','wire','gold','momentous','yellow','cap','delicate','youthful','twig','burly','devilish','chess','wide','misty','useful','memorise','madly','plants','spectacular','accessible','collar','truck','harmony','uncovered','beef','low','channel','abusive','analyse','observant','snobbish','duck','excellent','intend','wreck','testy','care','shoes','charming','demonic','can','wipe','acidic','watch','decisive','brave','greet','imminent','influence','oranges','seal','eggs','knowledgeable','ashamed','shiny','inconclusive','remind','house','solid','quixotic','describe','support']; + const words = ['belief','scandalous','flawless','wrestle','sort','moldy','carve','incompetent','cruel','awful','fang','holistic','makeshift','synonymous','questionable','soft','drop','boot','whimsical','stir','idea','adhesive','present','hilarious','unusual','divergent','probable','depend','suck','belong','advise','straight','encouraging','wing','clam','serve','fill','nostalgic','dysfunctional','aggressive','floor','baby','grease','sisters','print','switch','control','victorious','cracker','dream','wistful','adaptable','reminiscent','inquisitive','pushy','unaccountable','receive','guttural','two','protect','skin','unbiased','plastic','loutish','zip','used','divide','communicate','dear','muddled','dinosaurs','grip','trees','well-off','calendar','chickens','irate','deranged','trip','stream','white','poison','attack','obtain','theory','laborer','omniscient','brake','maniacal','curvy','smoke','babies','punch','hammer','toothbrush','same','crown','jagged','peep','difficult','reject','merciful','useless','doctor','mix','wicked','plant','quickest','roll','suffer','curly','brother','frighten','cold','tremendous','move','knot','lame','imaginary','capricious','raspy','aunt','loving','wink','wooden','hop','free','drab','fire','instrument','border','frame','silent','glue','decorate','distance','powerful','pig','admit','fix','pour','flesh','profuse','skinny','learn','filthy','dress','bloody','produce','innocent','meaty','pray','slimy','sun','kindhearted','dime','exclusive','boast','neat','ruthless','recess','grieving','daily','hateful','ignorant','fence','spring','slim','education','overflow','plastic','gaping','chew','detect','right','lunch','gainful','argue','cloistered','horses','orange','shame','bitter','able','sail','magical','exist','force','wheel','best','suit','spurious','partner','request','dog','gusty','money','gaze','lonely','company','pale','tempt','rat','flame','wobble','superficial','stop','protective','stare','tongue','heal','railway','idiotic','roll','puffy','turn','meeting','new','frightening','sophisticated','poke','elderly','room','stimulating','increase','moor','secret','lean','occur','country','damp','evanescent','alluring','oafish','join','thundering','cars','awesome','advice','unruly','ray','wind','anxious','fly','hammer','adventurous','shop','cook','trucks','nonchalant','addition','base','abashed','excuse','giants','dramatic','piquant','coach','possess','poor','finger','wide-eyed','aquatic','welcome','instruct','expert','evasive','hug','cute','return','mice','damage','turkey','quiet','bewildered','tidy','pointless','outrageous','medical','foolish','curve','grandiose','gullible','hapless','gleaming','third','grin','pipe','egg','act','physical','eager','side','milk','tearful','fertile','average','glamorous','strange','yak','terrific','thin','near','snails','flowery','authority','fish','curious','perpetual','healthy','health','match','fade','chemical','economic','drawer','avoid','lying','minister','lick','powder','decay','desire','furry','faint','beam','sordid','fax','tail','bawdy','cherry','letter','clover','ladybug','teeth','behavior','black','amazing','pink','waste','island','forgetful','needless','lock','waves','boundary','receipt','handy','religion','hypnotic','aftermath','explain','sense','mundane','rambunctious','second','preserve','alarm','dusty','event','blow','weigh','value','glorious','jail','sigh','cemetery','serious','yummy','cattle','understood','limit','alert','fear','lucky','tested','surround','dolls','pleasant','disillusioned','discover','tray','night','seemly','liquid','worry','pen','bent','gruesome','war','teeny-tiny','common','judge','symptomatic','bed','trot','unequaled','flowers','friends','damaged','peel','skip','show','twist','worthless','brush','look','behave','imperfect','week','petite','direction','soda','lively','coal','coil','release','berserk','books','impossible','replace','cough','chunky','torpid','discreet','material','bomb','soothe','crack','hope','license','frightened','breathe','maddening','calculator','committee','paltry','green','subsequent','arrest','gigantic','tasty','metal','willing','man','stem','nonstop','route','impulse','government','comfortable','include','literate','multiply','test','vast','exercise','addicted','agreeable','lace','toes','young','water','end','wash','glossy','round','staking','sink','open','spot','trip','fierce','robust','pastoral','drown','dress','machine','calculating','holiday','crabby','disgusting','plan','sleet','sleepy','typical','borrow','possible','curtain','airplane','industry','nut','rough','wacky','rock','enormous','uninterested','sugar','rake','consist','wrist','basket','chop','wet','street','known','settle','bless','cluttered','wild','expand','angle','snake','yawn','hate','flood','rabid','spiteful','anger','market','bizarre','force','majestic','scissors','beg','rifle','foregoing','cactus','funny','eggnog','wish','high-pitched','drop','camp','scarf','car','groan','wonderful','wealthy','cup','lock','available','previous','jam','political','vacation','three','desk','fry','aspiring','productive','clear','bored','flashy','plug','precede','abhorrent','muddle','flimsy','paste','need','reward','frail','obnoxious','creature','whip','unbecoming','lake','unused','chin','tour','zephyr','experience','building','scrub','correct','hover','panicky','scorch','diligent','hulking','ubiquitous','tedious','aberrant','file','accidental','mist','blue-eyed','trite','nondescript','cows','wait','test','snotty','amuck','jump','lackadaisical','grey','tawdry','strong','land','kind','star','ludicrous','stupid','telling','use','bruise','whirl','cream','harsh','aboriginal','substantial','brawny','tease','pollution','weather','degree','dry','film','obey','closed','dependent','want','undesirable','stamp','relax','foot','obscene','successful','wriggle','drain','greasy','escape','cross','odd','boring','absorbed','houses','suppose','suit','moon','ceaseless','explode','clap','pop','courageous','miss','notebook','delirious','form','pretty','sock','grotesque','noxious','record','stop','saw','thing','dislike','cloth','six','jar','unnatural','spiffy','itchy','secretary','move','certain','unkempt','sassy','queue','shrug','crow','heavenly','desert','screw','vessel','mug','encourage','icy','enthusiastic','throat','whistle','ignore','miniature','squeak','scarecrow','fluttering','hang','icicle','lie','juicy','empty','baseball','various','promise','abortive','descriptive','high','spy','faded','talk','air','messup','decorous','sneaky','mark','sack','ultra','chivalrous','lethal','expect','disgusted','reaction','fireman','private','ritzy','manage','actor','rely','uppity','thread','bat','space','underwear','blood','nine','maid','shelf','hanging','shop','prick','wound','sloppy','offer','increase','clear','slap','rude','poised','wretched','cause','quince','tame','remarkable','abject','sail','guide','subdued','spiky','debonair','chicken','tired','hum','land','scared','splendid','guess','cast','rub','magnificent','ants','overwrought','interfere','gorgeous','office','trade','sniff','melted','bore','point','pet','purple','brake','flavor','toe','prickly','zinc','homely','modern','kindly','whisper','bare','annoyed','glass','noisy','null','thoughtless','skirt','dock','rings','mind','neck','macho','wave','history','play','road','profit','word','opposite','dreary','governor','horse','trust','elbow','kiss','crayon','stitch','excited','needy','arrange','easy','alcoholic','safe','lumpy','monkey','smile','capable','untidy','extra-small','memory','selective','reproduce','old-fashioned','overrated','texture','knit','downtown','risk','pot','sofa','righteous','wren','pull','carry','aboard','listen','classy','thank','shocking','condition','root','attempt','swim','frog','hurt','army','title','handsomely','town','guiltless','thaw','spell','selfish','disturbed','tramp','girls','utopian','noiseless','trail','bashful','business','rhetorical','snail','sign','plausible','left','design','tall','violent','wasteful','beautiful','breezy','tap','murder','talented','needle','creator','imagine','flippant','dead','bone','coherent','relation','aromatic','mountainous','face','ask','picture','pedal','colour','obese','group','top','bubble','pinch','optimal','school','bathe','flagrant','check','deliver','pass','tan','crate','hose','debt','faulty','longing','hollow','invincible','afford','lovely','ticket','changeable','subtract','fumbling','responsible','confused','woman','touch','watch','zesty','library','jail','wrap','terrify','brick','popcorn','cooperative','peck','pocket','property','buzz','tiresome','digestion','exciting','nation','juvenile','shade','copper','wanting','deer','waste','man','join','spotty','amused','mountain','waggish','bushes','tense','river','heartbreaking','help','mine','narrow','smash','scrawny','tame','rain','playground','airport','astonishing','level','befitting','animal','heat','painful','cellar','ski','sedate','knowing','vigorous','change','eight','ship','work','strip','robin','tank','challenge','vacuous','representative','regret','tightfisted','erratic','club','imported','therapeutic','rainstorm','luxuriant','relieved','day','system','apologise','male','prepare','malicious','naive','whistle','curl','hobbies','trousers','stereotyped','dad','endurable','grass','hot','bomb','morning','guide','keen','plot','accept','disastrous','macabre','year','spicy','absorbing','sticks','efficient','drain','warm','rice','utter','fact','marked','ratty','chalk','towering','treat','nest','annoy','jealous','stamp','effect','cautious','jelly','feigned','gabby','corn','volleyball','pan','psychedelic','fairies','silent','zonked','bump','trouble','mass','queen','things','bury','sister','quiet','colossal','puncture','four','attend','love','wiry','vegetable','destruction','note','pies','resolute','load','fancy','tacky','periodic','abandoned','vivacious','blush','wrathful','miscreant','call','striped','wiggly','supreme','hand','impolite','rule','deserted','concern','cover','harbor','waiting','soggy','psychotic','ancient','sponge','domineering','elegant','impartial','unlock','abrasive','count','flight','neighborly','roof','bulb','auspicious','automatic','magic','sign','amusing','orange','branch','sulky','attack','fetch','number','jellyfish','start','alike','touch','sour','wary','minor','punish','connect','protest','pie','kaput','doubtful','friendly','simplistic','smart','vanish','applaud','jumbled','ready','yell','support','squash','raise','parallel','super','jazzy','crush','apathetic','water','food','thrill','permit','heady','last','mine','signal','smoke','preach','x-ray','name','birth','minute','steel','bedroom','female','acrid','riddle','attractive','earth','crack','muscle','alive','guarded','sweater','donkey','doubt','lettuce','magenta','live','farm','glib','bow','fascinated','friend','practise','remember','bleach','hungry','voiceless','pin','sparkling','report','arm','sad','shaggy','parcel','wail','flash','territory','functional','wise','screeching','appliance','future','appear','team','rabbit','porter','paint','flat','amusement','ocean','head','geese','wash','embarrassed','tub','boundless','freezing','mushy','surprise','temporary','marble','recondite','telephone','zipper','pine','reign','pump','tangy','reply','toys','purpose','songs','form','delicious','wood','horn','nutty','fruit','lumber','potato','cheat','cloudy','visit','reduce','destroy','deafening','full','warlike','mitten','cover','earthy','seashore','yarn','tenuous','pause','boil','dogs','tough','knife','shy','naughty','existence','fire','eminent','remove','juice','sleep','voyage','balance','unsightly','plough','ill-fated','pumped','motionless','allow','trade','warm','toad','wave','wall','pigs','circle','rejoice','ear','drink','found','taboo','object','old','temper','plant','public','picayune','blot','delight','carpenter','dispensable','tire','cow','furniture','rightful','mute','gentle','gifted','ragged','stiff','retire','compare','sable','hole','judicious','chilly','sparkle','futuristic','love','bubble','travel','name','numberless','succeed','acoustic','lowly','society','injure','agree','reason','party','wool','careful','hook','bell','ball','attach','scream','development','happy','appreciate','disagree','request','march','rampant','scrape','sack','hair','measure','owe','grubby','vein','boy','punishment','smoggy','wry','immense','shoe','pack','brash','cave','sincere','adorable','fantastic','attraction','racial','jittery','defiant','honey','paper','weight','bee','blind','birthday','toothsome','trick','guard','fog','handle','dirty','salt','rinse','nippy','observe','suggestion','weak','instinctive','frequent','detail','verse','quirky','scattered','toy','aware','distribution','repulsive','draconian','bucket','harm','radiate','bang','shrill','living','rhythm','obsequious','drum','inject','skate','beds','smash','order','stitch','ground','nosy','kick','dusty','home','rot','frame','jam','sky','soap','rescue','energetic','grape','massive','deeply','dazzling','park','pull','number','abundant','barbarous','drag','ajar','close','moan','haircut','shade','married','cats','thirsty','dirt','vagabond','fearful','squealing','squalid','zebra','murky','sheet','fat','follow','bikes','unpack','materialistic','surprise','arch','selection','acoustics','helpless','thoughtful','cry','quarrelsome','arrogant','illegal','sudden','elite','tomatoes','spoil','flower','shivering','front','caption','volcano','ugliest','ambitious','pickle','interrupt','nervous','approve','messy','dust','oceanic','brass','tremble','fine','nerve','lunchroom','hard','engine','erect','flower','cynical','irritating','tight','cobweb','gray','invention','snatch','account','sharp','spooky','squeamish','eatable','share','need','moaning','suspect','rush','rural','false','float','bite','careless','sidewalk','cowardly','stroke','educated','ugly','type','wandering','bolt','mint','fit','large','extra-large','defeated','kitty','tacit','abiding','grandfather','trains','lamp','habitual','fast','offbeat','accurate','many','fortunate','lyrical','charge','illustrious','transport','wakeful','cable','ordinary','string','question','train','fancy','kick','enchanting','jobless','ahead','comparison','loose','dance','add','wonder','stale','earn','reflective','bright','true','statuesque','amount','matter','repair','care','ruin','terrible','elastic','spiders','craven','lamentable','decision','swing','connection','gaudy','knowledge','cheap','lazy','step','dinner','rod','agreement','comb','mean','past','knotty','busy','quicksand','match','early','long','onerous','ambiguous','worried','spade','happen','crook','dapper','grate','announce','plate','haunt','friction','actually','chance','example','rapid','zealous','necessary','ink','mere','shock','huge','jaded','spill','store','fuzzy','table','bottle','halting','spark','end','remain','transport','seat','leg','long-term','clip','grumpy','shake','walk','try','action','soup','short','hurry','square','belligerent','thankful','beginner','small','bumpy','silly','badge','marvelous','wealth','open','unequal','scatter','pest','fool','step','groovy','childlike','door','bouncy','believe','incredible','box','unhealthy','swanky','abrupt','depressed','flaky','famous','detailed','regret','envious','natural','apparel','spare','mark','ten','power','glistening','arrive','animated','slip','heap','shaky','unfasten','contain','inexpensive','introduce','shallow','rule','gather','pump','humorous','acceptable','womanly','giddy','silk','yoke','straw','invite','one','red','growth','unadvised','measly','flap','puzzled','regular','painstaking','little','plain','tumble','rest','fabulous','melt','label','truculent','internal','passenger','zippy','bright','earsplitting','tooth','veil','grip','square','stuff','gate','level','stone','observation','time','workable','bird','realise','spotted','coast','quiver','rebel','entertain','rotten','loss','collect','meal','satisfy','military','bake','cagey','redundant','treatment','knock','blink','scale','board','fair','nebulous','sip','homeless','place','complain','joke','bat','winter','choke','frantic','chubby','highfalutin','troubled','whole','rose','delightful','loaf','afraid','sturdy','class','cultured','yielding','broken','kittens','absurd','discovery','next','disarm','dangerous','lively','reflect','chief','teeny','pencil','ban','grade','size','dashing','thought','breath','empty','hellish','shock','sea','weary','payment','limping','premium','grateful','somber','tax','coach','vulgar','stretch','tow','branch','insurance','yam','stormy','wish','snow','cute','milky','battle','far','roasted','slip','adamant','awake','employ','tangible','tickle','jog','hysterical','meddle','parsimonious','judge','educate','respect','sound','oven','gratis','station','train','purring','steady','carriage','humdrum','voracious','jolly','brainy','proud','elfin','cure','motion','record','quizzical','pail','bike','faithful','approval','vague','fall','store','normal','rock','bear','bounce','giant','satisfying','crooked','lopsided','vest','separate','sneeze','teaching','general','meat','festive','historical','line','north','tip','son','damaging','nimble','broad','list','confuse','first','deserve','steep','last','rich','oval','thick','glow','great','clammy','cheer','untidy','scientific','noise','stomach','undress','big','bite-sized','enter','cake','aloof','abnormal','month','grab','well-groomed','silver','art','berry','giraffe','complete','billowy','thumb','squeal','crib','discussion','even','stretch','mellow','angry','grouchy','absent','snow','middle','stingy','mourn','deep','honorable','nice','verdant','reach','lavish','sin','interest','whine','tug','vengeful','rhyme','stay','upset','hesitant','tent','wire','gold','momentous','yellow','cap','delicate','youthful','twig','burly','devilish','chess','wide','misty','useful','memorise','madly','plants','spectacular','accessible','collar','truck','harmony','uncovered','beef','low','channel','abusive','analyse','observant','snobbish','duck','excellent','intend','wreck','testy','care','shoes','charming','demonic','can','wipe','acidic','watch','decisive','brave','greet','imminent','influence','oranges','seal','eggs','knowledgeable','ashamed','shiny','inconclusive','remind','house','solid','quixotic','describe','support']; return randomElement(words); } @@ -88,7 +88,7 @@ function execCommand(client, command, options = {}) { async function execRandomCommand(client) { let possibleCommands = [ ['mkbook {word}', 40], // CREATE FOLDER - ['mknote {word}', 100], // CREATE NOTE + ['mknote {word}', 70], // CREATE NOTE [async () => { // DELETE RANDOM ITEM let items = await execCommand(client, 'dump'); items = JSON.parse(items); @@ -107,12 +107,12 @@ async function execRandomCommand(client) { let avgSyncDuration = averageSyncDuration(); let options = {}; if (!isNaN(avgSyncDuration)) { - // if (Math.random() >= 0.5) { - // options.killAfter = avgSyncDuration * Math.random(); - // } + if (Math.random() >= 0.5) { + options.killAfter = avgSyncDuration * Math.random(); + } } return execCommand(client, 'sync --random-failures', options); - }, 40], + }, 30], [async () => { // UPDATE RANDOM ITEM let items = await execCommand(client, 'dump'); items = JSON.parse(items); @@ -263,8 +263,7 @@ async function main(argv) { logger.error(error); }).then((r) => { if (r) { - logger.info('Client ' + clientId + ':'); - logger.info(r); + logger.info('Client ' + clientId + ":\n" + r.trim()) } clients[clientId].activeCommandCount--; }); diff --git a/CliClient/app/import-enex.js b/CliClient/app/import-enex.js index 190d267fb..737e23101 100644 --- a/CliClient/app/import-enex.js +++ b/CliClient/app/import-enex.js @@ -76,7 +76,7 @@ async function saveNoteResources(note) { } async function saveNoteTags(note) { - let noteTagged = 0; + let notesTagged = 0; for (let i = 0; i < note.tags.length; i++) { let tagTitle = note.tags[i]; @@ -85,9 +85,9 @@ async function saveNoteTags(note) { await Tag.addNote(tag.id, note.id); - noteTagged++; + notesTagged++; } - return noteTagged; + return notesTagged; } async function saveNoteToStorage(note, fuzzyMatching = false) { @@ -100,14 +100,14 @@ async function saveNoteToStorage(note, fuzzyMatching = false) { noteUpdated: false, noteSkipped: false, resourcesCreated: 0, - noteTagged: 0, + notesTagged: 0, }; let resourcesCreated = await saveNoteResources(note); result.resourcesCreated += resourcesCreated; - let noteTagged = await saveNoteTags(note); - result.noteTagged += noteTagged; + let notesTagged = await saveNoteTags(note); + result.notesTagged += notesTagged; if (existingNote) { let diff = BaseModel.diffObjects(existingNote, note); @@ -148,7 +148,7 @@ function importEnex(parentFolderId, filePath, importOptions = null) { updated: 0, skipped: 0, resourcesCreated: 0, - noteTagged: 0, + notesTagged: 0, }; let stream = fs.createReadStream(filePath); @@ -213,7 +213,7 @@ function importEnex(parentFolderId, filePath, importOptions = null) { progressState.skipped++; } progressState.resourcesCreated += result.resourcesCreated; - progressState.noteTagged += result.noteTagged; + progressState.notesTagged += result.notesTagged; importOptions.onProgress(progressState); }); }); diff --git a/CliClient/app/main.js b/CliClient/app/main.js index 594ec8744..0ce78dc57 100644 --- a/CliClient/app/main.js +++ b/CliClient/app/main.js @@ -391,8 +391,8 @@ commands.push({ if (report.remotesToDelete) line.push(_('Remote items to delete: %d/%d.', report.deleteRemote, report.remotesToDelete)); if (report.localsToUdpate) line.push(_('Items to download: %d/%d.', report.createLocal + report.updateLocal, report.localsToUdpate)); if (report.localsToDelete) line.push(_('Local items to delete: %d/%d.', report.deleteLocal, report.localsToDelete)); - //redrawnCalled = true; - //vorpal.ui.redraw(line.join(' ')); + // redrawnCalled = true; + // vorpal.ui.redraw(line.join(' ')); }, onMessage: (msg) => { if (redrawnCalled) vorpal.ui.redraw.done(); diff --git a/CliClient/tests/test-utils.js b/CliClient/tests/test-utils.js index 7a84ad134..98b2b8eb8 100644 --- a/CliClient/tests/test-utils.js +++ b/CliClient/tests/test-utils.js @@ -45,7 +45,6 @@ function clearDatabase(id = null) { if (id === null) id = currentClient_; let queries = [ - 'DELETE FROM changes', 'DELETE FROM notes', 'DELETE FROM folders', 'DELETE FROM resources', diff --git a/lib/base-model.js b/lib/base-model.js index 8d7df89b8..130f7cef0 100644 --- a/lib/base-model.js +++ b/lib/base-model.js @@ -37,10 +37,6 @@ class BaseModel { throw new Error('Must be overriden'); } - static trackChanges() { - return false; - } - static trackDeleted() { return false; } @@ -106,7 +102,6 @@ class BaseModel { } else { options = Object.assign({}, options); } - if (!('trackChanges' in options)) options.trackChanges = true; if (!('trackDeleted' in options)) options.trackDeleted = null; if (!('isNew' in options)) options.isNew = 'auto'; if (!('autoTimestamp' in options)) options.autoTimestamp = true; @@ -321,6 +316,7 @@ BaseModel.MODEL_TYPE_NOTE = 1; BaseModel.MODEL_TYPE_FOLDER = 2; BaseModel.MODEL_TYPE_SETTING = 3; BaseModel.MODEL_TYPE_RESOURCE = 4; +BaseModel.MODEL_TYPE_TAG = 5; BaseModel.tableInfo_ = null; BaseModel.tableKeys_ = null; BaseModel.db_ = null; diff --git a/lib/database.js b/lib/database.js index ec8654574..04e78d3bc 100644 --- a/lib/database.js +++ b/lib/database.js @@ -60,7 +60,8 @@ CREATE TABLE tags ( id TEXT PRIMARY KEY, title TEXT NOT NULL DEFAULT "", created_time INT NOT NULL, - updated_time INT NOT NULL + updated_time INT NOT NULL, + sync_time INT NOT NULL DEFAULT 0 ); CREATE TABLE note_tags ( @@ -79,14 +80,6 @@ CREATE TABLE resources ( sync_time INT NOT NULL DEFAULT 0 ); -CREATE TABLE changes ( - id INTEGER PRIMARY KEY, - \`type\` INT, - item_id TEXT, - item_type INT, - item_field TEXT -); - CREATE TABLE settings ( \`key\` TEXT PRIMARY KEY, \`value\` TEXT, diff --git a/lib/models/base-item.js b/lib/models/base-item.js index 38719424d..a9493fe93 100644 --- a/lib/models/base-item.js +++ b/lib/models/base-item.js @@ -32,6 +32,7 @@ class BaseItem extends BaseModel { if (Number(item) === BaseModel.MODEL_TYPE_NOTE) return this.getClass('Note'); if (Number(item) === BaseModel.MODEL_TYPE_FOLDER) return this.getClass('Folder'); if (Number(item) === BaseModel.MODEL_TYPE_RESOURCE) return this.getClass('Resource'); + if (Number(item) === BaseModel.MODEL_TYPE_TAG) return this.getClass('Tag'); throw new Error('Unknown type: ' + item); } } @@ -40,7 +41,9 @@ class BaseItem extends BaseModel { static async syncedItems() { let folders = await this.getClass('Folder').modelSelectAll('SELECT id FROM folders WHERE sync_time > 0'); let notes = await this.getClass('Note').modelSelectAll('SELECT id FROM notes WHERE is_conflict = 0 AND sync_time > 0'); - return folders.concat(notes); + let resources = await this.getClass('Resource').modelSelectAll('SELECT id FROM resources WHERE sync_time > 0'); + let tags = await this.getClass('Tag').modelSelectAll('SELECT id FROM tags WHERE sync_time > 0'); + return folders.concat(notes).concat(resources).concat(tags); } static pathToId(path) { @@ -52,11 +55,13 @@ class BaseItem extends BaseModel { return this.loadItemById(this.pathToId(path)); } - static loadItemById(id) { - return this.getClass('Note').load(id).then((item) => { + static async loadItemById(id) { + let classes = ['Note', 'Folder', 'Resource', 'Tag']; + for (let i = 0; i < classes.length; i++) { + let item = await this.getClass(classes[i]).load(id); if (item) return item; - return this.getClass('Folder').load(id); - }); + } + return null; } static loadItemByField(itemType, field, value) { @@ -86,7 +91,7 @@ class BaseItem extends BaseModel { } static unserialize_format(type, propName, propValue) { - if (propName == 'type_') return propValue; + if (propName[propName.length - 1] == '_') return propValue; // Private property let ItemClass = this.itemClass(type); @@ -110,9 +115,17 @@ class BaseItem extends BaseModel { output.push(type == 'note' ? item.body : ''); output.push(''); for (let i = 0; i < shownKeys.length; i++) { - let v = item[shownKeys[i]]; - v = this.serialize_format(shownKeys[i], v); - output.push(shownKeys[i] + ': ' + v); + let key = shownKeys[i]; + let value = null; + if (typeof key === 'function') { + let r = await key(); + key = r.key; + value = r.value; + } else { + value = this.serialize_format(key, item[key]); + } + + output.push(key + ': ' + value); } return output.join("\n"); @@ -170,6 +183,9 @@ class BaseItem extends BaseModel { if (items.length) return { hasMore: true, items: items }; items = await this.getClass('Note').modelSelectAll('SELECT * FROM notes WHERE sync_time < updated_time AND is_conflict = 0 LIMIT ' + limit); + if (items.length) return { hasMore: true, items: items }; + + items = await this.getClass('Tag').modelSelectAll('SELECT * FROM tags WHERE sync_time < updated_time LIMIT ' + limit); return { hasMore: items.length >= limit, items: items }; } diff --git a/lib/models/change.js b/lib/models/change.js deleted file mode 100644 index eefd991a9..000000000 --- a/lib/models/change.js +++ /dev/null @@ -1,101 +0,0 @@ -import { BaseModel } from 'lib/base-model.js'; -import { Log } from 'lib/log.js'; - -class Change extends BaseModel { - - static tableName() { - return 'changes'; - } - - static newChange() { - return { - id: null, - type: null, - item_id: null, - item_type: null, - item_field: null, - }; - } - - static all() { - return this.db().selectAll('SELECT * FROM changes'); - } - - static deleteMultiple(ids) { - if (ids.length == 0) return Promise.resolve(); - - let queries = []; - for (let i = 0; i < ids.length; i++) { - queries.push(['DELETE FROM changes WHERE id = ?', [ids[i]]]); - } - - return this.db().transactionExecBatch(queries); - } - - static mergeChanges(changes) { - let createdItems = []; - let deletedItems = []; - let itemChanges = {}; - - for (let i = 0; i < changes.length; i++) { - let change = changes[i]; - let mergedChange = null; - - if (itemChanges[change.item_id]) { - mergedChange = itemChanges[change.item_id]; - } else { - mergedChange = { - item_id: change.item_id, - item_type: change.item_type, - fields: [], - ids: [], - type: change.type, - } - } - - if (change.type == this.TYPE_CREATE) { - createdItems.push(change.item_id); - } else if (change.type == this.TYPE_DELETE) { - deletedItems.push(change.item_id); - } else if (change.type == this.TYPE_UPDATE) { - if (mergedChange.fields.indexOf(change.item_field) < 0) { - mergedChange.fields.push(change.item_field); - } - } - - mergedChange.ids.push(change.id); - - itemChanges[change.item_id] = mergedChange; - } - - let output = []; - - for (let itemId in itemChanges) { - if (!itemChanges.hasOwnProperty(itemId)) continue; - let change = itemChanges[itemId]; - - if (createdItems.indexOf(itemId) >= 0 && deletedItems.indexOf(itemId) >= 0) { - // Item both created then deleted - skip - change.type = this.TYPE_NOOP; - } else if (deletedItems.indexOf(itemId) >= 0) { - // Item was deleted at some point - just return one 'delete' event - change.type = this.TYPE_DELETE; - } else if (createdItems.indexOf(itemId) >= 0) { - // Item was created then updated - just return one 'create' event with the latest changes - change.type = this.TYPE_CREATE; - } - - output.push(change); - } - - return output; - } - -} - -Change.TYPE_NOOP = 0; -Change.TYPE_CREATE = 1; -Change.TYPE_UPDATE = 2; -Change.TYPE_DELETE = 3; - -export { Change }; \ No newline at end of file diff --git a/lib/models/folder.js b/lib/models/folder.js index 4f26e1255..2b6d37777 100644 --- a/lib/models/folder.js +++ b/lib/models/folder.js @@ -25,10 +25,6 @@ class Folder extends BaseItem { return BaseModel.MODEL_TYPE_FOLDER; } - static trackChanges() { - return true; - } - static trackDeleted() { return true; } diff --git a/lib/models/note.js b/lib/models/note.js index 18b4d4729..ec0708c30 100644 --- a/lib/models/note.js +++ b/lib/models/note.js @@ -24,10 +24,6 @@ class Note extends BaseItem { return BaseModel.MODEL_TYPE_NOTE; } - static trackChanges() { - return true; - } - static trackDeleted() { return true; } diff --git a/lib/models/tag.js b/lib/models/tag.js index c9a642548..5c83ec203 100644 --- a/lib/models/tag.js +++ b/lib/models/tag.js @@ -16,17 +16,31 @@ class Tag extends BaseItem { static async serialize(item, type = null, shownKeys = null) { let fieldNames = this.fieldNames(); fieldNames.push('type_'); - fieldNames.push(() => { - + fieldNames.push(async () => { + let noteIds = await this.tagNoteIds(item.id); + console.info('NOTE IDS', noteIds); + return { + key: 'notes_', + value: noteIds.join(','), + }; }); lodash.pull(fieldNames, 'sync_time'); return super.serialize(item, 'tag', fieldNames); } - static tagNoteIds(tagId) { - return this.db().selectAll('SELECT note_id FROM note_tags WHERE tag_id = ?', [tagId]); + static async tagNoteIds(tagId) { + let rows = await this.db().selectAll('SELECT note_id FROM note_tags WHERE tag_id = ?', [tagId]); + let output = []; + for (let i = 0; i < rows.length; i++) { + output.push(rows[i].note_id); + } + return output; } + // TODO: in order for a sync to happen, the updated_time property should somehow be changed + // whenever an tag is applied or removed from an item. Either the updated_time property + // is changed here or by the caller? + static async addNote(tagId, noteId) { let hasIt = await this.hasNote(tagId, noteId); if (hasIt) return; @@ -35,7 +49,30 @@ class Tag extends BaseItem { tag_id: tagId, note_id: noteId, }); - return this.db().exec(query); + + await this.db().exec(query); + //await this.save({ id: tagId, updated_time: time.unixMs() }); //type_: BaseModel.MODEL_TYPE_TAG + } + + static async addNotes(tagId, noteIds) { + for (let i = 0; i < noteIds.length; i++) { + await this.addNote(tagId, noteIds[i]); + } + } + + // Note: updated_time must not change since this is only called from + // the synchronizer, which manages and sets the correct updated_time + static async setAssociatedNotes(tagId, noteIds) { + let queries = [{ + sql: 'DELETE FROM note_tags WHERE tag_id = ?', + params: [tagId], + }]; + + for (let i = 0; i < noteIds.length; i++) { + queries.push(Database.insertQuery('note_tags', { tag_id: tagId, note_id: noteIds[i] })); + } + + return this.db().transactionExecBatch(queries); } static async hasNote(tagId, noteId) { diff --git a/lib/synchronizer.js b/lib/synchronizer.js index dff572dde..da05ed6b1 100644 --- a/lib/synchronizer.js +++ b/lib/synchronizer.js @@ -331,6 +331,11 @@ class Synchronizer { } } + if (newContent.type_ == BaseModel.MODEL_TYPE_TAG) { + let noteIds = newContent.notes_.split(','); + await ItemClass.setAssociatedNotes(newContent.id, noteIds); + } + this.logSyncOperation(action, local, content, reason); } else { this.logSyncOperation(action, local, remote, reason);