CCMain.m 255 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732
  1. //
  2. // CCMain.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCMain.h"
  24. #import "AppDelegate.h"
  25. #import "CCPhotosCameraUpload.h"
  26. #import "CCSynchronize.h"
  27. #import "CCTransfersCell.h"
  28. #import "OCActivity.h"
  29. #import "OCNotifications.h"
  30. #import "OCNotificationsAction.h"
  31. #import "OCFrameworkConstants.h"
  32. #import "OCCapabilities.h"
  33. #import "CTAssetCheckmark.h"
  34. #import "NCBridgeSwift.h"
  35. #define alertCreateFolder 1
  36. #define alertCreateFolderCrypto 2
  37. #define alertRename 3
  38. #define alertOfflineFolder 4
  39. @interface CCMain () <CCActionsDeleteDelegate, CCActionsRenameDelegate, CCActionsSearchDelegate, CCActionsDownloadThumbnailDelegate, CCActionsSettingFavoriteDelegate>
  40. {
  41. tableMetadata *_metadata;
  42. BOOL _isRoot;
  43. BOOL _isViewDidLoad;
  44. BOOL _isOfflineServerUrl;
  45. BOOL _isPickerCriptate; // if is cryptated image or video back from picker
  46. BOOL _isSelectedMode;
  47. NSMutableArray *_selectedMetadatas;
  48. NSMutableArray *_queueSelector;
  49. NSUInteger _numSelectedMetadatas;
  50. UIImageView *_ImageTitleHomeCryptoCloud;
  51. UIView *_reMenuBackgroundView;
  52. UITapGestureRecognizer *_singleFingerTap;
  53. NSString *_directoryGroupBy;
  54. NSString *_directoryOrder;
  55. NSUInteger _failedAttempts;
  56. NSDate *_lockUntilDate;
  57. NSString *_fatherPermission;
  58. UIRefreshControl *_refreshControl;
  59. UIDocumentInteractionController *_docController;
  60. CCHud *_hud;
  61. CCHud *_hudDeterminate;
  62. // Datasource
  63. CCSectionDataSourceMetadata *_sectionDataSource;
  64. NSDate *_dateReadDataSource;
  65. // Search
  66. BOOL _isSearchMode;
  67. NSString *_searchFileName;
  68. NSMutableArray *_searchResultMetadatas;
  69. NSString *_depth;
  70. NSString *_noFilesSearchTitle;
  71. NSString *_noFilesSearchDescription;
  72. // Login
  73. CCLoginWeb *_loginWeb;
  74. CCLogin *_loginVC;
  75. }
  76. @end
  77. @implementation CCMain
  78. #pragma --------------------------------------------------------------------------------------------
  79. #pragma mark ===== Init =====
  80. #pragma --------------------------------------------------------------------------------------------
  81. - (id)initWithCoder:(NSCoder *)aDecoder
  82. {
  83. if (self = [super initWithCoder:aDecoder]) {
  84. _directoryOrder = [CCUtility getOrderSettings];
  85. _directoryGroupBy = [CCUtility getGroupBySettings];
  86. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  87. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  88. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  89. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  90. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  91. }
  92. return self;
  93. }
  94. #pragma --------------------------------------------------------------------------------------------
  95. #pragma mark ===== View =====
  96. #pragma --------------------------------------------------------------------------------------------
  97. - (void)viewDidLoad
  98. {
  99. [super viewDidLoad];
  100. // init object
  101. _metadata = [tableMetadata new];
  102. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  103. _hudDeterminate = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  104. _selectedMetadatas = [NSMutableArray new];
  105. _queueSelector = [NSMutableArray new];
  106. _sectionDataSource = [CCSectionDataSourceMetadata new];
  107. _isViewDidLoad = YES;
  108. _fatherPermission = @"";
  109. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  110. _searchResultMetadatas = [NSMutableArray new];
  111. _searchFileName = @"";
  112. _depth = @"0";
  113. _noFilesSearchTitle = @"";
  114. _noFilesSearchDescription = @"";
  115. // delegate
  116. self.tableView.delegate = self;
  117. self.tableView.tableFooterView = [UIView new];
  118. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  119. self.tableView.emptyDataSetDelegate = self;
  120. self.tableView.emptyDataSetSource = self;
  121. self.searchController.delegate = self;
  122. self.searchController.searchBar.delegate = self;
  123. [[CCNetworking sharedNetworking] settingDelegate:self];
  124. // Custom Cell
  125. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  126. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  127. // long press recognizer TableView
  128. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  129. [self.tableView addGestureRecognizer:longPressRecognizer];
  130. // Pull-to-Refresh
  131. [self createRefreshControl];
  132. // Register for 3D Touch Previewing if available
  133. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  134. {
  135. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  136. }
  137. // Back Button
  138. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]])
  139. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"] style:UIBarButtonItemStylePlain target:nil action:nil];
  140. // reMenu Background
  141. _reMenuBackgroundView = [[UIView alloc] init];
  142. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  143. // if this is not Main (the Main uses inizializeMain)
  144. if (_isRoot == NO && app.activeAccount.length > 0) {
  145. // Settings this folder & delegate & Loading datasource
  146. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  147. // Load Datasource
  148. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  149. // Read Folder
  150. [self readFolderWithForced:NO serverUrl:_serverUrl];
  151. }
  152. // Title
  153. [self setTitle];
  154. // Search
  155. self.definesPresentationContext = YES;
  156. self.searchController.searchResultsUpdater = self;
  157. self.searchController.dimsBackgroundDuringPresentation = NO;
  158. self.tableView.tableHeaderView = self.searchController.searchBar;
  159. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].seperator;
  160. [self.searchController.searchBar sizeToFit];
  161. self.searchController.searchBar.delegate = self;
  162. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  163. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  164. if (_isRoot)
  165. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_all_folders_",nil), nil];
  166. else
  167. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),NSLocalizedString(@"_search_sub_folder_",nil), nil];
  168. } else {
  169. self.searchController.searchBar.scopeButtonTitles = nil;
  170. }
  171. // Hide Search Filed on Load
  172. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  173. }
  174. // Apparirà
  175. - (void)viewWillAppear:(BOOL)animated
  176. {
  177. [super viewWillAppear:animated];
  178. // test
  179. if (app.activeAccount.length == 0)
  180. return;
  181. // Settings this folder & delegate & Loading datasource
  182. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  183. [[CCNetworking sharedNetworking] settingDelegate:self];
  184. // Color
  185. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  186. [app aspectTabBar:self.tabBarController.tabBar hidden:NO];
  187. if (_isSelectedMode)
  188. [self setUINavigationBarSelected];
  189. else
  190. [self setUINavigationBarDefault];
  191. // Plus Button
  192. [app plusButtonVisibile:true];
  193. }
  194. // E' arrivato
  195. - (void)viewDidAppear:(BOOL)animated
  196. {
  197. [super viewDidAppear:animated];
  198. // Active Main
  199. app.activeMain = self;
  200. // Test viewDidLoad
  201. if (_isViewDidLoad) {
  202. _isViewDidLoad = NO;
  203. } else {
  204. if (app.activeAccount.length > 0) {
  205. // Load Datasource
  206. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  207. // Read Folder
  208. [self readFolderWithForced:NO serverUrl:_serverUrl];
  209. }
  210. }
  211. // Title
  212. [self setTitle];
  213. }
  214. - (void)viewWillDisappear:(BOOL)animated
  215. {
  216. [super viewWillDisappear:animated];
  217. [self closeAllMenu];
  218. }
  219. - (void)didReceiveMemoryWarning
  220. {
  221. [super didReceiveMemoryWarning];
  222. // Dispose of any resources that can be recreated.
  223. }
  224. - (BOOL)prefersStatusBarHidden
  225. {
  226. return NO;
  227. }
  228. // detect scroll for remove keyboard in search mode
  229. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  230. {
  231. if (_isSearchMode && scrollView == self.tableView) {
  232. [self.searchController.searchBar endEditing:YES];
  233. }
  234. }
  235. - (void)changeTheming
  236. {
  237. if (self.isViewLoaded && self.view.window)
  238. [app changeTheming:self];
  239. // Refresh control
  240. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  241. // Reload Table View
  242. [self.tableView reloadData];
  243. }
  244. #pragma --------------------------------------------------------------------------------------------
  245. #pragma mark ===== Initizlize Mail =====
  246. #pragma --------------------------------------------------------------------------------------------
  247. - (void)initializeMain:(NSNotification *)notification
  248. {
  249. _directoryGroupBy = nil;
  250. _directoryOrder = nil;
  251. _dateReadDataSource = nil;
  252. // test
  253. if (app.activeAccount.length == 0)
  254. return;
  255. if ([app.listMainVC count] == 0 || _isRoot) {
  256. // This is Root
  257. _isRoot = YES;
  258. // Crypto Mode
  259. if ([[CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]] length] == 0) {
  260. app.isCryptoCloudMode = NO;
  261. } else {
  262. app.isCryptoCloudMode = YES;
  263. }
  264. // go Home
  265. [self.navigationController popToRootViewControllerAnimated:NO];
  266. // Remove search mode
  267. [self cancelSearchBar];
  268. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:app.activeUrl];
  269. _isFolderEncrypted = NO;
  270. app.directoryUser = [CCUtility getDirectoryActiveUser:app.activeUser activeUrl:app.activeUrl];
  271. // add list
  272. [app.listMainVC setObject:self forKey:_serverUrl];
  273. // setting Networking
  274. [[CCNetworking sharedNetworking] settingDelegate:self];
  275. [[CCNetworking sharedNetworking] settingAccount];
  276. // populate shared Link & User variable
  277. NSArray *results = [[NCManageDatabase sharedInstance] getShares];
  278. if (results) {
  279. app.sharesLink = results[0];
  280. app.sharesUserAndGroup = results[1];
  281. }
  282. // Setting Theming
  283. [app settingThemingColorBrand];
  284. // Load Datasource
  285. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  286. // Load Folder
  287. [self readFolderWithForced:NO serverUrl:_serverUrl];
  288. // Load photo datasorce
  289. if (app.activePhotosCameraUpload)
  290. [app.activePhotosCameraUpload reloadDatasourceForced];
  291. // remove all of detail
  292. if (app.activeDetail)
  293. [app.activeDetail removeAllView];
  294. // remove all Notification Messages
  295. [app.listOfNotifications removeAllObjects];
  296. // home main
  297. app.homeMain = self;
  298. // Initializations
  299. [app applicationInitialized];
  300. } else {
  301. // reload datasource
  302. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  303. }
  304. }
  305. #pragma --------------------------------------------------------------------------------------------
  306. #pragma mark ==== DZNEmptyDataSetSource ====
  307. #pragma --------------------------------------------------------------------------------------------
  308. /*
  309. - (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView
  310. {
  311. if(_isSearchMode)
  312. return NO;
  313. else
  314. return YES;
  315. }
  316. */
  317. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  318. {
  319. return YES;
  320. }
  321. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  322. {
  323. return [UIColor whiteColor];
  324. }
  325. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  326. {
  327. if (_isSearchMode)
  328. return [UIImage imageNamed:@"searchBig"];
  329. else
  330. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] color:[NCBrandColor sharedInstance].brand];
  331. }
  332. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  333. {
  334. NSString *text;
  335. if (_isSearchMode)
  336. text = _noFilesSearchTitle;
  337. else
  338. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  339. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  340. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  341. }
  342. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  343. {
  344. NSString *text;
  345. if (_isSearchMode)
  346. text = _noFilesSearchDescription;
  347. else
  348. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  349. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  350. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  351. paragraph.alignment = NSTextAlignmentCenter;
  352. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  353. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  354. }
  355. #pragma --------------------------------------------------------------------------------------------
  356. #pragma mark ===== AlertView =====
  357. #pragma --------------------------------------------------------------------------------------------
  358. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  359. {
  360. [alertView dismissWithClickedButtonIndex:buttonIndex animated:YES];
  361. if (alertView.tag == alertCreateFolder && buttonIndex == 1) [self createFolder:[alertView textFieldAtIndex:0].text folderCameraUpload:NO];
  362. if (alertView.tag == alertCreateFolderCrypto && buttonIndex == 1) [self createFolderEncrypted:[alertView textFieldAtIndex:0].text];
  363. if (alertView.tag == alertRename && buttonIndex == 1) {
  364. if ([_metadata.model isEqualToString:@"note"]) {
  365. [self renameNote:_metadata fileName:[alertView textFieldAtIndex:0].text];
  366. } else {
  367. [self renameFile:_metadata fileName:[alertView textFieldAtIndex:0].text];
  368. }
  369. }
  370. if (alertView.tag == alertOfflineFolder && buttonIndex == 1) {
  371. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  372. NSString *dir = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  373. [[CCSynchronize sharedSynchronize] addOfflineFolder:dir];
  374. [self performSelector:@selector(reloadDatasource) withObject:nil];
  375. }
  376. }
  377. // accept only number char > 0
  378. - (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
  379. {
  380. /* Retrieve a text field at an index -
  381. raises NSRangeException when textFieldIndex is out-of-bounds.
  382. The field at index 0 will be the first text field
  383. (the single field or the login field),
  384. The field at index 1 will be the password field. */
  385. /*
  386. 1> Get the Text Field in alertview
  387. 2> Get the text of that Text Field
  388. 3> Verify that text length
  389. 4> return YES or NO Based on the length
  390. */
  391. if (alertView.tag == alertOfflineFolder) return YES;
  392. else return ([[[alertView textFieldAtIndex:0] text] length]>0)?YES:NO;
  393. }
  394. #pragma --------------------------------------------------------------------------------------------
  395. #pragma mark ===== Graphic Window =====
  396. #pragma --------------------------------------------------------------------------------------------
  397. - (void)createRefreshControl
  398. {
  399. _refreshControl = [UIRefreshControl new];
  400. _refreshControl.tintColor = [NCBrandColor sharedInstance].brand;
  401. _refreshControl.backgroundColor = [UIColor colorWithRed:235.0/255.0 green:235.0/255.0 blue:235.0/255.0 alpha:1.0];
  402. [_refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  403. [self setRefreshControl:_refreshControl];
  404. }
  405. - (void)deleteRefreshControl
  406. {
  407. [_refreshControl endRefreshing];
  408. self.refreshControl = nil;
  409. }
  410. - (void)refreshControlTarget
  411. {
  412. [self readFolderWithForced:YES serverUrl:_serverUrl];
  413. // Actuate `Peek` feedback (weak boom)
  414. AudioServicesPlaySystemSound(1519);
  415. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  416. }
  417. - (void)setTitle
  418. {
  419. // Color text self.navigationItem.title
  420. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  421. if (_isSelectedMode) {
  422. NSUInteger totali = [_sectionDataSource.allRecordsDataSource count];
  423. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  424. self.navigationItem.titleView = nil;
  425. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  426. } else {
  427. // we are in home : LOGO BRAND
  428. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:app.activeUrl]]) {
  429. self.navigationItem.title = nil;
  430. if ([app.reachability isReachable] == NO)
  431. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogoOffline"]];
  432. else
  433. _ImageTitleHomeCryptoCloud = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"navigationLogo"]];
  434. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  435. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo)];
  436. [singleTap setNumberOfTapsRequired:1];
  437. [_ImageTitleHomeCryptoCloud addGestureRecognizer:singleTap];
  438. self.navigationItem.titleView = _ImageTitleHomeCryptoCloud;
  439. } else {
  440. self.navigationItem.title = _titleMain;
  441. }
  442. }
  443. }
  444. - (void)setUINavigationBarDefault
  445. {
  446. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  447. UIBarButtonItem *buttonMore, *buttonNotification;
  448. // =
  449. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  450. buttonMore.enabled = true;
  451. // <
  452. self.navigationController.navigationBar.hidden = NO;
  453. // Notification
  454. if ([app.listOfNotifications count] > 0) {
  455. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  456. buttonNotification.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  457. buttonNotification.enabled = true;
  458. }
  459. if (buttonNotification)
  460. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  461. else
  462. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  463. self.navigationItem.leftBarButtonItem = nil;
  464. }
  465. - (void)setUINavigationBarSelected
  466. {
  467. [app aspectNavigationControllerBar:self.navigationController.navigationBar encrypted:_isFolderEncrypted online:[app.reachability isReachable] hidden:NO];
  468. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  469. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  470. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  471. self.navigationItem.leftBarButtonItem = leftButton;
  472. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  473. }
  474. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  475. {
  476. [self closeAllMenu];
  477. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  478. }];
  479. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  480. }
  481. - (void)cancelSelect
  482. {
  483. [self tableViewSelect:NO];
  484. [app.reSelectMenu close];
  485. }
  486. - (void)closeAllMenu
  487. {
  488. // close Menu
  489. [app.reSelectMenu close];
  490. [app.reMainMenu close];
  491. // Close Menu Logo
  492. [CCMenuAccount dismissMenu];
  493. }
  494. #pragma --------------------------------------------------------------------------------------------
  495. #pragma mark ===== Document Picker =====
  496. #pragma --------------------------------------------------------------------------------------------
  497. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  498. {
  499. NSLog(@"Cancelled");
  500. }
  501. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  502. {
  503. NSLog(@"Cancelled");
  504. }
  505. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  506. {
  507. documentPicker.delegate = self;
  508. [self presentViewController:documentPicker animated:YES completion:nil];
  509. }
  510. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  511. {
  512. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  513. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  514. __block NSError *error;
  515. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  516. NSString *fileName = [url lastPathComponent];
  517. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileName];
  518. NSData *data = [NSData dataWithContentsOfURL:newURL];
  519. if (data && error == nil) {
  520. if ([data writeToFile:fileNamePath options:NSDataWritingAtomic error:&error]) {
  521. // Upload File
  522. [[CCNetworking sharedNetworking] uploadFile:fileName serverUrl:_serverUrl cryptated:_isPickerCriptate onlyPlist:NO session:k_upload_session taskStatus: k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  523. } else {
  524. [app messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  525. }
  526. } else {
  527. [app messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  528. }
  529. }];
  530. }
  531. }
  532. - (void)openImportDocumentPicker
  533. {
  534. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  535. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  536. documentProviderMenu.popoverPresentationController.sourceView = self.view;
  537. documentProviderMenu.popoverPresentationController.sourceRect = self.view.bounds;
  538. documentProviderMenu.delegate = self;
  539. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  540. }
  541. #pragma --------------------------------------------------------------------------------------------
  542. #pragma mark ===== Assets Picker =====
  543. #pragma --------------------------------------------------------------------------------------------
  544. - (void)openAssetsPickerController
  545. {
  546. CTAssetCheckmark *checkmark = [CTAssetCheckmark appearance];
  547. checkmark.tintColor = [NCBrandColor sharedInstance].brand;
  548. [checkmark setMargin:0.0 forVerticalEdge:NSLayoutAttributeRight horizontalEdge:NSLayoutAttributeTop];
  549. UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:[CTAssetsPickerController class], nil];
  550. [app aspectNavigationControllerBar:navBar encrypted:NO online:YES hidden:NO];
  551. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
  552. dispatch_async(dispatch_get_main_queue(), ^{
  553. // init picker
  554. CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
  555. // set delegate
  556. picker.delegate = self;
  557. // to show selection order
  558. //picker.showsSelectionIndex = YES;
  559. // to present picker as a form sheet in iPad
  560. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  561. picker.modalPresentationStyle = UIModalPresentationFormSheet;
  562. // present picker
  563. [self presentViewController:picker animated:YES completion:nil];
  564. });
  565. }];
  566. }
  567. - (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSMutableArray *)assets
  568. {
  569. [picker dismissViewControllerAnimated:YES completion:^{
  570. CreateFormUploadAssets *form = [[CreateFormUploadAssets alloc] init:_titleMain serverUrl:_serverUrl assets:assets cryptated:_isPickerCriptate session:k_upload_session];
  571. form.title = NSLocalizedString(@"_upload_photos_videos_", nil);
  572. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  573. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  574. //navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
  575. [self presentViewController:navigationController animated:YES completion:nil];
  576. }];
  577. }
  578. #pragma --------------------------------------------------------------------------------------------
  579. #pragma mark ===== UIDocumentInteractionControllerDelegate =====
  580. #pragma --------------------------------------------------------------------------------------------
  581. - (void)documentInteractionControllerDidDismissOptionsMenu:(UIDocumentInteractionController *)controller
  582. {
  583. // evitiamo il rimando della eventuale photo e/o video
  584. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountActive];
  585. if (tableAccount.cameraUpload) {
  586. [[NCManageDatabase sharedInstance] setAccountCameraUploadDateAssetType:PHAssetMediaTypeImage assetDate:[NSDate date]];
  587. [[NCManageDatabase sharedInstance] setAccountCameraUploadDateAssetType:PHAssetMediaTypeVideo assetDate:[NSDate date]];
  588. }
  589. }
  590. #pragma --------------------------------------------------------------------------------------------
  591. #pragma mark ===== UnZipFile =====
  592. #pragma --------------------------------------------------------------------------------------------
  593. - (void)unZipFile:(NSString *)fileID
  594. {
  595. [_hudDeterminate visibleHudTitle:NSLocalizedString(@"_unzip_in_progress_", nil) mode:MBProgressHUDModeDeterminate color:nil];
  596. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  597. NSString *fileZip = [NSString stringWithFormat:@"%@/%@", app.directoryUser, fileID];
  598. [SSZipArchive unzipFileAtPath:fileZip toDestination:[CCUtility getDirectoryLocal] overwrite:YES password:nil progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {
  599. dispatch_async(dispatch_get_main_queue(), ^{
  600. float progress = (float) entryNumber / (float)total;
  601. [_hudDeterminate progress:progress];
  602. });
  603. } completionHandler:^(NSString *path, BOOL succeeded, NSError *error) {
  604. dispatch_async(dispatch_get_main_queue(), ^{
  605. [_hudDeterminate hideHud];
  606. if (succeeded) [app messageNotification:@"_info_" description:@"_file_unpacked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  607. else [app messageNotification:@"_error_" description:[NSString stringWithFormat:@"Error %ld", (long)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  608. });
  609. }];
  610. });
  611. }
  612. #pragma --------------------------------------------------------------------------------------------
  613. #pragma mark ===== Create New (OpenModel) =====
  614. #pragma --------------------------------------------------------------------------------------------
  615. - (void)openModel:(NSString *)tipo isNew:(BOOL)isnew
  616. {
  617. UIViewController *viewController;
  618. NSString *fileName, *uuid, *fileID, *serverUrl;
  619. NSIndexPath * index = [self.tableView indexPathForSelectedRow];
  620. [self.tableView deselectRowAtIndexPath:index animated:NO];
  621. if (isnew) {
  622. fileName = nil;
  623. uuid = [CCUtility getUUID];
  624. fileID = nil;
  625. serverUrl = _serverUrl;
  626. } else {
  627. fileName = _metadata.fileName;
  628. uuid = _metadata.uuid;
  629. fileID = _metadata.fileID;
  630. serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  631. }
  632. if ([tipo isEqualToString:@"cartadicredito"])
  633. viewController = [[CCCartaDiCredito alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  634. if ([tipo isEqualToString:@"bancomat"])
  635. viewController = [[CCBancomat alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  636. if ([tipo isEqualToString:@"contocorrente"])
  637. viewController = [[CCContoCorrente alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  638. if ([tipo isEqualToString:@"accountweb"])
  639. viewController = [[CCAccountWeb alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  640. if ([tipo isEqualToString:@"patenteguida"])
  641. viewController = [[CCPatenteGuida alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  642. if ([tipo isEqualToString:@"cartaidentita"])
  643. viewController = [[CCCartaIdentita alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  644. if ([tipo isEqualToString:@"passaporto"])
  645. viewController = [[CCPassaporto alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  646. if ([tipo isEqualToString:@"note"]) {
  647. viewController = [[CCNote alloc] initWithDelegate:self fileName:fileName uuid:uuid fileID:fileID isLocal:NO serverUrl:serverUrl];
  648. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  649. [self presentViewController:navigationController animated:YES completion:nil];
  650. } else {
  651. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  652. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  653. [self presentViewController:navigationController animated:YES completion:nil];
  654. }
  655. }
  656. // New folder or new photo or video
  657. - (void)returnCreate:(NSInteger)type
  658. {
  659. switch (type) {
  660. /* PLAIN */
  661. case k_returnCreateFolderPlain: {
  662. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  663. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  664. alertView.tag = alertCreateFolder;
  665. [alertView show];
  666. }
  667. break;
  668. case k_returnCreateFotoVideoPlain: {
  669. _isPickerCriptate = false;
  670. [self openAssetsPickerController];
  671. }
  672. break;
  673. case k_returnCreateFilePlain: {
  674. _isPickerCriptate = false;
  675. [self openImportDocumentPicker];
  676. }
  677. break;
  678. /* ENCRYPTED */
  679. case k_returnCreateFolderEncrypted: {
  680. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_create_folder_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  681. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  682. alertView.tag = alertCreateFolderCrypto;
  683. [alertView show];
  684. }
  685. break;
  686. case k_returnCreateFotoVideoEncrypted: {
  687. _isPickerCriptate = true;
  688. [self openAssetsPickerController];
  689. }
  690. break;
  691. case k_returnCreateFileEncrypted: {
  692. _isPickerCriptate = true;
  693. [self openImportDocumentPicker];
  694. }
  695. break;
  696. /* UTILITY */
  697. case k_returnNote:
  698. [self openModel:@"note" isNew:true];
  699. break;
  700. case k_returnAccountWeb:
  701. [self openModel:@"accountweb" isNew:true];
  702. break;
  703. /* BANK */
  704. case k_returnCartaDiCredito:
  705. [self openModel:@"cartadicredito" isNew:true];
  706. break;
  707. case k_returnBancomat:
  708. [self openModel:@"bancomat" isNew:true];
  709. break;
  710. case k_returnContoCorrente:
  711. [self openModel:@"contocorrente" isNew:true];
  712. break;
  713. /* DOCUMENT */
  714. case k_returnPatenteGuida:
  715. [self openModel:@"patenteguida" isNew:true];
  716. break;
  717. case k_returnCartaIdentita:
  718. [self openModel:@"cartaidentita" isNew:true];
  719. break;
  720. case k_returnPassaporto:
  721. [self openModel:@"passaporto" isNew:true];
  722. break;
  723. }
  724. }
  725. #pragma --------------------------------------------------------------------------------------------
  726. #pragma mark ===== Save selected File =====
  727. #pragma --------------------------------------------------------------------------------------------
  728. -(void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  729. {
  730. if (error)
  731. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  732. else
  733. [app messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  734. }
  735. - (void)saveSelectedFiles
  736. {
  737. NSLog(@"[LOG] Start download selected files ...");
  738. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  739. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  740. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  741. for (tableMetadata *metadata in metadatas) {
  742. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file] && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  743. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  744. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorSave selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  745. }
  746. }
  747. [_hud hideHud];
  748. });
  749. [self tableViewSelect:NO];
  750. }
  751. #pragma --------------------------------------------------------------------------------------------
  752. #pragma mark ===== Change Password =====
  753. #pragma --------------------------------------------------------------------------------------------
  754. - (void) loginSuccess:(NSInteger)loginType
  755. {
  756. [self readFolderWithForced:YES serverUrl:_serverUrl];
  757. }
  758. - (void)changePasswordAccount
  759. {
  760. // Brand
  761. if ([NCBrandOptions sharedInstance].use_login_web) {
  762. _loginWeb = [CCLoginWeb new];
  763. _loginWeb.delegate = self;
  764. _loginWeb.loginType = loginModifyPasswordUser;
  765. dispatch_async(dispatch_get_main_queue(), ^ {
  766. [_loginWeb presentModalWithDefaultTheme:self];
  767. });
  768. } else {
  769. _loginVC = [[UIStoryboard storyboardWithName:@"CCLogin" bundle:nil] instantiateViewControllerWithIdentifier:@"CCLoginNextcloud"];
  770. _loginVC.delegate = self;
  771. _loginVC.loginType = loginModifyPasswordUser;
  772. [self presentViewController:_loginVC animated:YES completion:nil];
  773. }
  774. }
  775. #pragma mark -
  776. #pragma --------------------------------------------------------------------------------------------
  777. #pragma mark ===== Peek & Pop =====
  778. #pragma --------------------------------------------------------------------------------------------
  779. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  780. {
  781. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  782. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  783. if (metadata.thumbnailExists && !metadata.cryptated) {
  784. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  785. if (cell) {
  786. previewingContext.sourceRect = cell.frame;
  787. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  788. vc.delegate = self;
  789. vc.metadata = metadata;
  790. return vc;
  791. }
  792. }
  793. return nil;
  794. }
  795. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  796. {
  797. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  798. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  799. }
  800. #pragma mark -
  801. #pragma --------------------------------------------------------------------------------------------
  802. #pragma mark ==== External Sites ====
  803. #pragma --------------------------------------------------------------------------------------------
  804. - (void)getExternalSitesServerSuccess:(NSArray *)listOfExternalSites
  805. {
  806. [[NCManageDatabase sharedInstance] deleteExternalSites];
  807. for (OCExternalSites *tableExternalSites in listOfExternalSites)
  808. [[NCManageDatabase sharedInstance] addExternalSites:tableExternalSites];
  809. }
  810. - (void)getExternalSitesServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  811. {
  812. NSLog(@"[LOG] No External Sites found");
  813. }
  814. #pragma --------------------------------------------------------------------------------------------
  815. #pragma mark ==== Activity ====
  816. #pragma --------------------------------------------------------------------------------------------
  817. - (void)getActivityServerSuccess:(NSArray *)listOfActivity
  818. {
  819. [[NCManageDatabase sharedInstance] addActivityServer:listOfActivity];
  820. // Reload Activity Data Source
  821. [app.activeActivity reloadDatasource];
  822. }
  823. - (void)getActivityServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  824. {
  825. NSLog(@"[LOG] No Activity found");
  826. }
  827. #pragma --------------------------------------------------------------------------------------------
  828. #pragma mark ==== Notification ====
  829. #pragma --------------------------------------------------------------------------------------------
  830. - (void)getNotificationServerSuccess:(NSArray *)listOfNotifications
  831. {
  832. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  833. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  834. // Order by date
  835. NSArray *sortedListOfNotifications = [listOfNotifications sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
  836. OCNotifications *notification1 = obj1, *notification2 = obj2;
  837. return [notification2.date compare: notification1.date];
  838. }];
  839. // verify if listOfNotifications is changed
  840. NSString *old = @"", *new = @"";
  841. for (OCNotifications *notification in listOfNotifications)
  842. new = [new stringByAppendingString:@(notification.idNotification).stringValue];
  843. for (OCNotifications *notification in appDelegate.listOfNotifications)
  844. old = [old stringByAppendingString:@(notification.idNotification).stringValue];
  845. if (![new isEqualToString:old]) {
  846. appDelegate.listOfNotifications = [[NSMutableArray alloc] initWithArray:sortedListOfNotifications];
  847. // reload Notification view
  848. dispatch_async(dispatch_get_main_queue(), ^{
  849. [[NSNotificationCenter defaultCenter] postNotificationName:@"notificationReloadData" object:nil];
  850. });
  851. }
  852. // Update NavigationBar
  853. if (!_isSelectedMode) {
  854. [self performSelectorOnMainThread:@selector(setUINavigationBarDefault) withObject:nil waitUntilDone:NO];
  855. }
  856. });
  857. }
  858. - (void)getNotificationServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  859. {
  860. // Update NavigationBar
  861. if (!_isSelectedMode)
  862. [self setUINavigationBarDefault];
  863. }
  864. - (void)viewNotification
  865. {
  866. if ([app.listOfNotifications count] > 0) {
  867. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  868. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  869. [self presentViewController:notificationVC animated:YES completion:nil];
  870. }
  871. }
  872. #pragma --------------------------------------------------------------------------------------------
  873. #pragma mark ==== User Profile ====
  874. #pragma --------------------------------------------------------------------------------------------
  875. - (void)getUserProfileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  876. {
  877. if (errorCode == 401)
  878. [self changePasswordAccount];
  879. }
  880. - (void)getUserProfileSuccess:(CCMetadataNet *)metadataNet userProfile:(OCUserProfile *)userProfile
  881. {
  882. [[NCManageDatabase sharedInstance] setAccountsUserProfile:userProfile];
  883. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  884. NSString *address = [NSString stringWithFormat:@"%@/index.php/avatar/%@/128", app.activeUrl, app.activeUser];
  885. UIImage *avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  886. if (avatar)
  887. [UIImagePNGRepresentation(avatar) writeToFile:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] atomically:YES];
  888. else
  889. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/avatar.png", app.directoryUser] error:nil];
  890. dispatch_async(dispatch_get_main_queue(), ^{
  891. [[NSNotificationCenter defaultCenter] postNotificationName:@"changeUserProfile" object:nil];
  892. });
  893. });
  894. }
  895. #pragma --------------------------------------------------------------------------------------------
  896. #pragma mark ==== Capabilities ====
  897. #pragma --------------------------------------------------------------------------------------------
  898. - (void)getCapabilitiesOfServerFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  899. {
  900. // Change Theming color
  901. [app settingThemingColorBrand];
  902. if (errorCode == 401)
  903. [self changePasswordAccount];
  904. }
  905. - (void)getCapabilitiesOfServerSuccess:(OCCapabilities *)capabilities
  906. {
  907. // Update capabilities db
  908. [[NCManageDatabase sharedInstance] addCapabilities:capabilities];
  909. // ------ THEMING -----------------------------------------------------------------------
  910. // Download Theming Background & Change Theming color
  911. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  912. if ([NCBrandOptions sharedInstance].use_themingBackground == YES) {
  913. UIImage *themingBackground = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[capabilities.themingBackground stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]];
  914. if (themingBackground)
  915. [UIImagePNGRepresentation(themingBackground) writeToFile:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] atomically:YES];
  916. else
  917. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/themingBackground.png", app.directoryUser] error:nil];
  918. }
  919. dispatch_async(dispatch_get_main_queue(), ^{
  920. [app settingThemingColorBrand];
  921. });
  922. });
  923. // ------ SEARCH ------------------------------------------------------------------------
  924. // Search bar if change version
  925. if ([[NCManageDatabase sharedInstance] getServerVersion] != capabilities.versionMajor) {
  926. [self cancelSearchBar];
  927. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  928. if (capabilities.versionMajor >= 12) {
  929. if (_isRoot)
  930. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_all_folders_",nil);
  931. else
  932. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_sub_folder_",nil);
  933. self.searchController.searchBar.scopeButtonTitles = [NSArray arrayWithObjects:NSLocalizedString(@"_search_this_folder_",nil),self.searchController.searchBar.placeholder, nil];
  934. } else {
  935. self.searchController.searchBar.placeholder = NSLocalizedString(@"_search_this_folder_",nil);
  936. self.searchController.searchBar.scopeButtonTitles = nil;
  937. }
  938. _depth = @"0";
  939. });
  940. }
  941. // ------ GET SERVICE SERVER ------------------------------------------------------------
  942. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  943. // Read External Sites
  944. if (capabilities.isExternalSitesServerEnabled) {
  945. metadataNet.action = actionGetExternalSitesServer;
  946. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  947. }
  948. // Read Share
  949. if (capabilities.isFilesSharingAPIEnabled) {
  950. [app.sharesID removeAllObjects];
  951. metadataNet.action = actionReadShareServer;
  952. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  953. }
  954. // Read Notification
  955. metadataNet.action = actionGetNotificationServer;
  956. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  957. // Read User Profile
  958. metadataNet.action = actionGetUserProfile;
  959. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  960. // Read Activity
  961. metadataNet.action = actionGetActivityServer;
  962. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  963. }
  964. #pragma mark -
  965. #pragma --------------------------------------------------------------------------------------------
  966. #pragma mark ==== Request Server Information ====
  967. #pragma --------------------------------------------------------------------------------------------
  968. - (void)requestServerCapabilities
  969. {
  970. // test
  971. if (app.activeAccount.length == 0)
  972. return;
  973. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  974. metadataNet.action = actionGetCapabilities;
  975. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  976. }
  977. #pragma mark -
  978. #pragma --------------------------------------------------------------------------------------------
  979. #pragma mark ==== Download Thumbnail Delegate ====
  980. #pragma --------------------------------------------------------------------------------------------
  981. - (void)downloadThumbnailSuccess:(CCMetadataNet *)metadataNet
  982. {
  983. __block CCCellMain *cell;
  984. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadataNet.fileID];
  985. if (indexPath && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]]) {
  986. cell = [self.tableView cellForRowAtIndexPath:indexPath];
  987. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadataNet.fileID];
  988. if (cell.fileImageView.image == nil) {
  989. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  990. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadataNet.fileID]];
  991. [app.icoImagesCache setObject:image forKey:metadataNet.fileID];
  992. });
  993. }
  994. }
  995. }
  996. #pragma --------------------------------------------------------------------------------------------
  997. #pragma mark ==== Download ====
  998. #pragma --------------------------------------------------------------------------------------------
  999. - (void)downloadFileFailure:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1000. {
  1001. //tableMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  1002. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount]];
  1003. // File do not exists on server, remove in local
  1004. if (errorCode == kOCErrorServerPathNotFound || errorCode == kCFURLErrorBadServerResponse) {
  1005. [CCCoreData deleteFile:metadata serverUrl:serverUrl directoryUser:app.directoryUser activeAccount:app.activeAccount];
  1006. }
  1007. if ([selector isEqualToString:selectorLoadViewImage]) {
  1008. dispatch_async(dispatch_get_main_queue(), ^{
  1009. // Updating Detail
  1010. if (app.activeDetail)
  1011. [app.activeDetail downloadPhotoBrowserFailure:errorCode];
  1012. // Updating Photos
  1013. if (app.activePhotosCameraUpload)
  1014. [app.activePhotosCameraUpload downloadFileFailure:errorCode];
  1015. });
  1016. } else {
  1017. if (errorCode != kCFURLErrorCancelled)
  1018. [app messageNotification:@"_download_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1019. }
  1020. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1021. }
  1022. - (void)downloadFileSuccess:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1023. {
  1024. //tableMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  1025. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount]];
  1026. if (metadata == nil) return;
  1027. // Download
  1028. if ([selector isEqualToString:selectorDownloadFile]) {
  1029. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1030. }
  1031. // Synchronized
  1032. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  1033. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1034. }
  1035. // add Favorite
  1036. if ([selector isEqualToString:selectorAddFavorite]) {
  1037. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  1038. }
  1039. // add Offline
  1040. if ([selector isEqualToString:selectorAddOffline]) {
  1041. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:YES activeAccount:app.activeAccount];
  1042. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1043. }
  1044. // encrypted file
  1045. if ([selector isEqualToString:selectorEncryptFile]) {
  1046. [self encryptedFile:metadata];
  1047. }
  1048. // decrypted file
  1049. if ([selector isEqualToString:selectorDecryptFile]) {
  1050. [self decryptedFile:metadata];
  1051. }
  1052. // open View File
  1053. if ([selector isEqualToString:selectorLoadFileView] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1054. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1055. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_compress]) {
  1056. [self performSelector:@selector(unZipFile:) withObject:metadata.fileID];
  1057. } else if ([metadata.typeFile isEqualToString: k_metadataTypeFile_unknown]) {
  1058. selector = selectorOpenIn;
  1059. } else {
  1060. _metadata = metadata;
  1061. if ([self shouldPerformSegue])
  1062. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  1063. }
  1064. }
  1065. // addLocal
  1066. if ([selector isEqualToString:selectorAddLocal]) {
  1067. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1068. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]];
  1069. [CCGraphics saveIcoWithFileID:metadata.fileNamePrint image:image writeToFile:nil copy:YES move:NO fromPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/.%@.ico", [CCUtility getDirectoryLocal], metadata.fileNamePrint]];
  1070. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  1071. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1072. }
  1073. // Open with...
  1074. if ([selector isEqualToString:selectorOpenIn] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1075. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1076. [[NSFileManager defaultManager] removeItemAtPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1077. [[NSFileManager defaultManager] linkItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1078. NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint]];
  1079. _docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1080. _docController.delegate = self;
  1081. [_docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1082. }
  1083. // Save to Photo Album
  1084. if ([selector isEqualToString:selectorSave] && [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive) {
  1085. NSString *file = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1086. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image]) {
  1087. // evitiamo il rimando photo
  1088. [[NCManageDatabase sharedInstance] setAccountCameraUploadDateAssetType:PHAssetMediaTypeImage assetDate:[NSDate date]];
  1089. UIImage *image = [UIImage imageWithContentsOfFile:file];
  1090. if (image)
  1091. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1092. else
  1093. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1094. }
  1095. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video]) {
  1096. // we avoid the cross-reference video
  1097. [[NCManageDatabase sharedInstance] setAccountCameraUploadDateAssetType:PHAssetMediaTypeVideo assetDate:[NSDate date]];
  1098. [[NSFileManager defaultManager] linkItemAtPath:file toPath:[NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint] error:nil];
  1099. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint])) {
  1100. UISaveVideoAtPathToSavedPhotosAlbum([NSTemporaryDirectory() stringByAppendingString:metadata.fileNamePrint], self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  1101. } else {
  1102. [app messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1103. }
  1104. }
  1105. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1106. }
  1107. // Copy File
  1108. if ([selector isEqualToString:selectorLoadCopy]) {
  1109. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1110. [self copyFileToPasteboard:metadata];
  1111. }
  1112. // download and view a template
  1113. if ([selector isEqualToString:selectorLoadModelView]) {
  1114. [CCCoreData downloadFilePlist:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl directoryUser:app.directoryUser];
  1115. [self openModel:metadata.model isNew:false];
  1116. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1117. }
  1118. //download file plist
  1119. if ([selector isEqualToString:selectorLoadPlist]) {
  1120. [CCCoreData downloadFilePlist:metadata activeAccount:app.activeAccount activeUrl:app.activeUrl directoryUser:app.directoryUser];
  1121. long countSelectorLoadPlist = 0;
  1122. for (NSOperation *operation in [app.netQueue operations]) {
  1123. if ([((OCnetworking *)operation).metadataNet.selector isEqualToString:selectorLoadPlist])
  1124. countSelectorLoadPlist++;
  1125. }
  1126. if ((countSelectorLoadPlist == 0 || countSelectorLoadPlist % k_maxConcurrentOperation == 0) && [metadata.directoryID isEqualToString:[CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount]]) {
  1127. dispatch_async(dispatch_get_main_queue(), ^{
  1128. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1129. });
  1130. }
  1131. }
  1132. //selectorLoadViewImage
  1133. if ([selector isEqualToString:selectorLoadViewImage]) {
  1134. dispatch_async(dispatch_get_main_queue(), ^{
  1135. // Detail
  1136. if (app.activeDetail)
  1137. [app.activeDetail downloadPhotoBrowserSuccess:metadata selector:selector];
  1138. // Photos
  1139. if (app.activePhotosCameraUpload)
  1140. [app.activePhotosCameraUpload downloadFileSuccess:metadata];
  1141. });
  1142. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:selector];
  1143. }
  1144. // if exists postselector call self with selectorPost
  1145. if ([selectorPost length] > 0)
  1146. [self downloadFileSuccess:fileID serverUrl:serverUrl selector:selectorPost selectorPost:nil];
  1147. }
  1148. - (void)downloadSelectedFiles
  1149. {
  1150. NSLog(@"[LOG] Start download selected files ...");
  1151. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1152. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1153. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  1154. for (tableMetadata *metadata in selectedMetadatas) {
  1155. if (metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_file]) {
  1156. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1157. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDownloadFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1158. }
  1159. }
  1160. [_hud hideHud];
  1161. });
  1162. [self tableViewSelect:NO];
  1163. }
  1164. - (void)downloadPlist:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1165. {
  1166. //NSArray *records = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND ((session == NULL) OR (session == ''))", app.activeAccount, directoryID] context:nil];
  1167. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPreficate:[NSPredicate predicateWithFormat:@"(account = %@) AND (directoryID = %@) AND (session = '')", app.activeAccount, directoryID] sorted:nil ascending:NO];
  1168. for (TableMetadata *recordMetadata in records) {
  1169. if ([CCUtility isCryptoPlistString:recordMetadata.fileName] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, recordMetadata.fileName]] == NO && [recordMetadata.session length] == 0) {
  1170. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1171. metadataNet.action = actionDownloadFile;
  1172. metadataNet.downloadData = NO;
  1173. metadataNet.downloadPlist = YES;
  1174. metadataNet.fileID = recordMetadata.fileID;
  1175. metadataNet.selector = selectorLoadPlist;
  1176. metadataNet.serverUrl = serverUrl;
  1177. metadataNet.session = k_download_session_foreground;
  1178. metadataNet.taskStatus = k_taskStatusResume;
  1179. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1180. }
  1181. }
  1182. }
  1183. #pragma --------------------------------------------------------------------------------------------
  1184. #pragma mark ===== Upload new Photos/Videos =====
  1185. #pragma --------------------------------------------------------------------------------------------
  1186. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1187. {
  1188. // Automatic upload All
  1189. if([selector isEqualToString:selectorUploadAutomaticAll])
  1190. [app performSelectorOnMainThread:@selector(loadAutomaticUpload) withObject:nil waitUntilDone:NO];
  1191. // Read File test do not exists
  1192. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1193. //tableMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  1194. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount]];
  1195. // reUpload
  1196. if (metadata)
  1197. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1198. }
  1199. // Print error
  1200. else if (errorCode != kCFURLErrorCancelled && errorCode != 403) {
  1201. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1202. }
  1203. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1204. }
  1205. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1206. {
  1207. // Automatic upload All
  1208. if([selector isEqualToString:selectorUploadAutomaticAll])
  1209. [app performSelectorOnMainThread:@selector(loadAutomaticUpload) withObject:nil waitUntilDone:NO];
  1210. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1211. [self readFolderWithForced:YES serverUrl:serverUrl];
  1212. } else {
  1213. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1214. }
  1215. }
  1216. //
  1217. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1218. //
  1219. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1220. {
  1221. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1222. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:cryptated], [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1223. });
  1224. }
  1225. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1226. {
  1227. NSArray *assets = [arguments objectAtIndex:0];
  1228. NSString *serverUrl = [arguments objectAtIndex:1];
  1229. BOOL cryptated = [[arguments objectAtIndex:2] boolValue];
  1230. BOOL useSubFolder = [[arguments objectAtIndex:3] boolValue];
  1231. NSString *session = [arguments objectAtIndex:4];
  1232. NSString *folderPhotos = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPathAndName:app.activeUrl];
  1233. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount];
  1234. // Create the folder for Photos & if request the subfolders
  1235. if (![app createFolderSubFolderAutomaticUploadFolderPhotos:folderPhotos useSubFolder:useSubFolder assets:assets selector:selectorUploadFile])
  1236. return;
  1237. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1238. for (PHAsset *asset in assets) {
  1239. NSString *fileName = [CCUtility createFileNameFromAsset:asset key: k_keyFileNameMask];
  1240. NSDate *assetDate = asset.creationDate;
  1241. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1242. // Create serverUrl if use sub folder
  1243. if (useSubFolder) {
  1244. [formatter setDateFormat:@"yyyy"];
  1245. NSString *yearString = [formatter stringFromDate:assetDate];
  1246. [formatter setDateFormat:@"MM"];
  1247. NSString *monthString = [formatter stringFromDate:assetDate];
  1248. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", folderPhotos, yearString, monthString];
  1249. }
  1250. // Check if is in upload
  1251. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(account = %@) AND (directoryID = %@) AND (fileName = %@) AND (session != '')", app.activeAccount, directoryID, fileName];
  1252. //NSArray *isRecordInSessions = [CCCoreData getTableMetadataWithPredicate:predicate context:nil];
  1253. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPreficate:predicate sorted:nil ascending:NO];
  1254. if ([isRecordInSessions count] > 0) {
  1255. // next upload
  1256. continue;
  1257. } else {
  1258. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1259. metadataNet.action = actionReadFile;
  1260. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1261. metadataNet.cryptated = cryptated;
  1262. metadataNet.fileName = fileName;
  1263. metadataNet.priority = NSOperationQueuePriorityNormal;
  1264. metadataNet.session = session;
  1265. metadataNet.selector = selectorReadFileUploadFile;
  1266. metadataNet.serverUrl = serverUrl;
  1267. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1268. }
  1269. }
  1270. }
  1271. #pragma --------------------------------------------------------------------------------------------
  1272. #pragma mark ==== Read File ====
  1273. #pragma --------------------------------------------------------------------------------------------
  1274. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1275. {
  1276. // UploadFile
  1277. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1278. // File not exists
  1279. if (errorCode == 404) {
  1280. metadataNet.action = actionUploadAsset;
  1281. metadataNet.errorCode = 0;
  1282. metadataNet.selector = selectorUploadFile;
  1283. metadataNet.selectorPost = nil;
  1284. metadataNet.taskStatus = k_taskStatusResume;
  1285. if ([metadataNet.session containsString:@"wwan"])
  1286. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1287. else
  1288. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1289. } else {
  1290. // error ho many retry befor notification and go to on next asses
  1291. if (metadataNet.errorRetry < 3) {
  1292. // Retry read file
  1293. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1294. } else {
  1295. // STOP check file, view message error
  1296. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1297. }
  1298. }
  1299. }
  1300. }
  1301. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1302. {
  1303. // UploadFile
  1304. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1305. metadataNet.action = actionUploadAsset;
  1306. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1307. metadataNet.selector = selectorUploadFile;
  1308. metadataNet.selectorPost = nil;
  1309. metadataNet.taskStatus = k_taskStatusResume;
  1310. if ([metadataNet.session containsString:@"wwan"])
  1311. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1312. else
  1313. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1314. }
  1315. }
  1316. #pragma --------------------------------------------------------------------------------------------
  1317. #pragma mark ==== Read Folder ====
  1318. #pragma --------------------------------------------------------------------------------------------
  1319. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1320. {
  1321. // verify active user
  1322. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1323. [_hud hideHud];
  1324. [_refreshControl endRefreshing];
  1325. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1326. if (message && [record.account isEqualToString:metadataNet.account])
  1327. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1328. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1329. if (errorCode == 401)
  1330. [self changePasswordAccount];
  1331. }
  1332. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet permissions:(NSString *)permissions etag:(NSString *)etag metadatas:(NSArray *)metadatas
  1333. {
  1334. // verify active user
  1335. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1336. if (![record.account isEqualToString:metadataNet.account])
  1337. return;
  1338. // save father e update permission
  1339. if(!_isSearchMode)
  1340. _fatherPermission = permissions;
  1341. NSArray *recordsInSessions;
  1342. if (_isSearchMode) {
  1343. //recordsInSessions = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session != NULL) AND (session != '')", metadataNet.account] context:nil];
  1344. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPreficate:[NSPredicate predicateWithFormat:@"(account = %@) AND (session != '')", metadataNet.account] sorted:nil ascending:NO];
  1345. } else {
  1346. [CCCoreData updateDirectoryEtagServerUrl:metadataNet.serverUrl etag:etag activeAccount:metadataNet.account];
  1347. //[CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND ((session == NULL) OR (session == ''))", metadataNet.account, metadataNet.directoryID]];
  1348. [[NCManageDatabase sharedInstance] deleteMetadata:[NSPredicate predicateWithFormat:@"(account = %@) AND (directoryID = %@) AND (session = '')", metadataNet.account, metadataNet.directoryID]];
  1349. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPreficate:[NSPredicate predicateWithFormat:@"(account = %@) AND (directoryID = %@) AND (session != '')", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1350. //recordsInSessions = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (session != NULL) AND (session != '')", metadataNet.account, metadataNet.directoryID] context:nil];
  1351. [CCCoreData setDateReadDirectoryID:metadataNet.directoryID activeAccount:app.activeAccount];
  1352. }
  1353. for (tableMetadata *metadata in metadatas) {
  1354. // Delete Record only in Search Mode
  1355. if (_isSearchMode) {
  1356. //[CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileID = %@) AND ((session == NULL) OR (session == ''))", metadataNet.account, metadata.directoryID, metadata.fileID]];
  1357. [[NCManageDatabase sharedInstance] deleteMetadata:[NSPredicate predicateWithFormat:@"(account = %@) AND (directoryID = %@) AND (fileID = %@) AND (session = '')", metadataNet.account, metadata.directoryID, metadata.fileID]];
  1358. }
  1359. // type of file
  1360. NSInteger typeFilename = [CCUtility getTypeFileName:metadata.fileName];
  1361. // if crypto do not insert
  1362. if (typeFilename == k_metadataTypeFilenameCrypto) continue;
  1363. // verify if the record encrypted has plist + crypto
  1364. if (typeFilename == k_metadataTypeFilenamePlist && metadata.directory == NO) {
  1365. BOOL isCryptoComplete = NO;
  1366. NSString *fileNameCrypto = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  1367. for (tableMetadata *completeMetadata in metadatas) {
  1368. if (completeMetadata.cryptated == NO) continue;
  1369. else if ([completeMetadata.fileName isEqualToString:fileNameCrypto]) {
  1370. isCryptoComplete = YES;
  1371. break;
  1372. }
  1373. }
  1374. if (isCryptoComplete == NO) continue;
  1375. }
  1376. // verify if the record is in download/upload progress
  1377. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1378. //tableMetadata *metadataDB = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileName == %@)", app.activeAccount, metadataNet.directoryID, metadata.fileName] context:nil];
  1379. tableMetadata *metadataDB = [[NCManageDatabase sharedInstance] getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileName == %@)", app.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1380. // is in Upload
  1381. if (metadataDB.session && [metadataDB.session containsString:@"upload"]) {
  1382. NSString *sessionID = metadataDB.sessionID;
  1383. // rename SessionID -> fileID
  1384. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]];
  1385. metadataDB.session = @"";
  1386. metadataDB.date = metadata.date;
  1387. metadataDB.fileID = metadata.fileID;
  1388. metadataDB.rev = metadata.fileID;
  1389. metadataDB.sessionError = @"";
  1390. metadataDB.sessionID = @"";
  1391. metadataDB.sessionTaskIdentifier = k_taskIdentifierDone;
  1392. metadataDB.sessionTaskIdentifierPlist = k_taskIdentifierDone;
  1393. //[CCCoreData updateMetadata:metadataDB predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, app.activeAccount] activeAccount:app.activeAccount activeUrl:app.activeUrl context:nil];
  1394. //[[NCManageDatabase sharedInstance] updateMetadata:metadataDB activeUrl:app.activeUrl];
  1395. [CCCoreData addLocalFile:metadataDB activeAccount:app.activeAccount];
  1396. [CCGraphics createNewImageFrom:metadata.fileID directoryUser:app.directoryUser fileNameTo:metadata.fileID fileNamePrint:metadata.fileNamePrint size:@"m" imageForUpload:NO typeFile:metadata.typeFile writePreview:YES optimizedFileName:[CCUtility getOptimizedPhoto]];
  1397. continue;
  1398. }
  1399. // download in progress
  1400. if (metadataDB.session && [metadataDB.session containsString:@"download"])
  1401. continue;
  1402. }
  1403. // end test, insert in CoreData
  1404. [[NCManageDatabase sharedInstance] addMetadata:metadata activeUrl:app.activeUrl];
  1405. }
  1406. // read plist
  1407. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1408. // File is changed ??
  1409. if (!_isSearchMode)
  1410. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatas serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1411. // Search Mode
  1412. if (_isSearchMode)
  1413. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1414. // this is the same directory
  1415. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1416. // reload
  1417. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1418. // stoprefresh
  1419. [_refreshControl endRefreshing];
  1420. // Enable change user
  1421. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1422. [_hud hideHud];
  1423. }
  1424. }
  1425. - (void)readFolderWithForced:(BOOL)forced serverUrl:(NSString *)serverUrl
  1426. {
  1427. // init control
  1428. if (!serverUrl || !app.activeAccount)
  1429. return;
  1430. // Search Mode
  1431. if (_isSearchMode) {
  1432. if (forced) {
  1433. [CCCoreData clearDateReadAccount:app.activeAccount serverUrl:serverUrl directoryID:nil];
  1434. _searchFileName = @""; // forced reload searchg
  1435. }
  1436. [self updateSearchResultsForSearchController:self.searchController];
  1437. return;
  1438. }
  1439. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount];
  1440. if ([CCCoreData isDirectoryOutOfDate:k_dayForceReadFolder directoryID:directoryID activeAccount:app.activeAccount] || forced) {
  1441. if (_refreshControl.isRefreshing == NO)
  1442. [_hud visibleIndeterminateHud];
  1443. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1444. metadataNet.action = actionReadFolder;
  1445. metadataNet.date = [NSDate date];
  1446. metadataNet.directoryID = directoryID;
  1447. metadataNet.priority = NSOperationQueuePriorityHigh;
  1448. metadataNet.selector = selectorReadFolder;
  1449. metadataNet.serverUrl = serverUrl;
  1450. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1451. }
  1452. }
  1453. #pragma mark -
  1454. #pragma --------------------------------------------------------------------------------------------
  1455. #pragma mark ===== Search =====
  1456. #pragma --------------------------------------------------------------------------------------------
  1457. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1458. {
  1459. _isSearchMode = YES;
  1460. [self deleteRefreshControl];
  1461. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1462. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1463. _searchFileName = fileName;
  1464. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12 && ![_depth isEqualToString:@"0"]) {
  1465. [[CCActions sharedInstance] search:_serverUrl fileName:_searchFileName depth:_depth delegate:self];
  1466. _noFilesSearchTitle = @"";
  1467. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1468. [self.tableView reloadEmptyDataSet];
  1469. } else {
  1470. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount];
  1471. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(directoryID == %@) AND (account == %@) AND (fileNamePrint CONTAINS[cd] %@)", directoryID, app.activeAccount, fileName];
  1472. //NSArray *records = [CCCoreData getTableMetadataWithPredicate:predicate context:nil];
  1473. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPreficate:predicate sorted:nil ascending:NO];
  1474. [_searchResultMetadatas removeAllObjects];
  1475. for (TableMetadata *record in records)
  1476. [_searchResultMetadatas addObject:[CCCoreData insertEntityInMetadata:record]];
  1477. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1478. metadataNet.account = app.activeAccount;
  1479. metadataNet.action = actionUploadTemplate;
  1480. metadataNet.directoryID = directoryID;
  1481. metadataNet.selector = selectorSearch;
  1482. metadataNet.serverUrl = _serverUrl;
  1483. [self readFolderSuccess:metadataNet permissions:@"" etag:@"" metadatas:_searchResultMetadatas];
  1484. }
  1485. }
  1486. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1487. [self reloadDatasource];
  1488. }
  1489. }
  1490. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1491. {
  1492. [self cancelSearchBar];
  1493. [self readFolderWithForced:NO serverUrl:_serverUrl];
  1494. }
  1495. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1496. {
  1497. _searchFileName = @"";
  1498. if (message)
  1499. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1500. }
  1501. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1502. {
  1503. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1504. [self readFolderSuccess:metadataNet permissions:nil etag:nil metadatas:metadatas];
  1505. }
  1506. - (void)cancelSearchBar
  1507. {
  1508. if (self.searchController.active) {
  1509. [self.searchController setActive:NO];
  1510. [self createRefreshControl];
  1511. _isSearchMode = NO;
  1512. _searchFileName = @"";
  1513. _dateReadDataSource = nil;
  1514. _searchResultMetadatas = [NSMutableArray new];
  1515. [self reloadDatasource];
  1516. }
  1517. }
  1518. - (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
  1519. {
  1520. NSString *title = [self.searchController.searchBar.scopeButtonTitles objectAtIndex:selectedScope];
  1521. self.searchController.searchBar.placeholder = title;
  1522. if ([title isEqualToString:NSLocalizedString(@"_search_this_folder_",nil)])
  1523. _depth = @"0";
  1524. if ([title isEqualToString:NSLocalizedString(@"_search_sub_folder_",nil)])
  1525. _depth = @"1";
  1526. if ([title isEqualToString:NSLocalizedString(@"_search_all_folders_",nil)])
  1527. _depth = @"infinity";
  1528. _searchFileName = @"";
  1529. [self updateSearchResultsForSearchController:self.searchController];
  1530. }
  1531. #pragma mark -
  1532. #pragma --------------------------------------------------------------------------------------------
  1533. #pragma mark ===== Delete File or Folder =====
  1534. #pragma --------------------------------------------------------------------------------------------
  1535. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1536. {
  1537. [self deleteFileOrFolderSuccess:metadataNet];
  1538. }
  1539. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1540. {
  1541. [_queueSelector removeObject:metadataNet.selector];
  1542. if ([_queueSelector count] == 0) {
  1543. [_hud hideHud];
  1544. if (_isSearchMode)
  1545. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1546. else
  1547. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1548. // next
  1549. if ([_selectedMetadatas count] > 0) {
  1550. [_selectedMetadatas removeObjectAtIndex:0];
  1551. if ([_selectedMetadatas count] > 0)
  1552. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1553. }
  1554. }
  1555. }
  1556. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1557. {
  1558. if (metadata.cryptated) {
  1559. [_queueSelector addObject:selectorDeleteCrypto];
  1560. [_queueSelector addObject:selectorDeletePlist];
  1561. } else {
  1562. [_queueSelector addObject:selectorDelete];
  1563. }
  1564. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1565. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1566. }
  1567. - (void)deleteSelectionFile
  1568. {
  1569. [_selectedMetadatas removeAllObjects];
  1570. [_queueSelector removeAllObjects];
  1571. _selectedMetadatas = [[NSMutableArray alloc] initWithArray: [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]]];
  1572. _numSelectedMetadatas = [_selectedMetadatas count];
  1573. if ([_selectedMetadatas count] > 0)
  1574. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1575. [self tableViewSelect:NO];
  1576. }
  1577. - (void)deleteFile
  1578. {
  1579. [_selectedMetadatas removeAllObjects];
  1580. [_queueSelector removeAllObjects];
  1581. _numSelectedMetadatas = 1;
  1582. [_selectedMetadatas addObject:_metadata];
  1583. if ([_selectedMetadatas count] > 0)
  1584. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1585. [self tableViewSelect:NO];
  1586. }
  1587. #pragma --------------------------------------------------------------------------------------------
  1588. #pragma mark ===== Rename / Move =====
  1589. #pragma --------------------------------------------------------------------------------------------
  1590. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1591. {
  1592. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1593. }
  1594. - (void)renameFile:(tableMetadata *)metadata fileName:(NSString *)fileName
  1595. {
  1596. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1597. }
  1598. - (void)renameNote:(tableMetadata *)metadata fileName:(NSString *)fileName
  1599. {
  1600. CCTemplates *templates = [[CCTemplates alloc] init];
  1601. NSMutableDictionary *field = [[CCCrypto sharedManager] getDictionaryEncrypted:metadata.fileName uuid:metadata.uuid isLocal:NO directoryUser:app.directoryUser];
  1602. NSString *fileNameModel = [templates salvaNote:[field objectForKey:@"note"] titolo:fileName fileName:metadata.fileName uuid:metadata.uuid];
  1603. if (fileNameModel) {
  1604. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1605. metadataNet.action = actionUploadTemplate;
  1606. metadataNet.fileName = [CCUtility trasformedFileNamePlistInCrypto:fileNameModel];
  1607. metadataNet.fileNamePrint = fileName;
  1608. metadataNet.rev = metadata.rev;
  1609. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1610. metadataNet.session = k_upload_session_foreground;
  1611. metadataNet.taskStatus = k_taskStatusResume;
  1612. if ([CCCoreData isOfflineLocalFileID:metadata.fileID activeAccount:app.activeAccount])
  1613. metadataNet.selectorPost = selectorAddOffline;
  1614. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1615. }
  1616. }
  1617. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1618. {
  1619. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1620. [_hud hideHud];
  1621. if (message)
  1622. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1623. [_selectedMetadatas removeAllObjects];
  1624. [_queueSelector removeAllObjects];
  1625. }
  1626. }
  1627. - (void)moveSuccess:(CCMetadataNet *)metadataNet revTo:(NSString *)revTo
  1628. {
  1629. [_queueSelector removeObject:metadataNet.selector];
  1630. if ([_queueSelector count] == 0) {
  1631. [_hud hideHud];
  1632. NSString *fileName = [CCUtility trasformedFileNameCryptoInPlist:metadataNet.fileName];
  1633. NSString *directoryID = metadataNet.directoryID;
  1634. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1635. NSString *serverUrlTo = [CCCoreData getServerUrlFromDirectoryID:directoryIDTo activeAccount:app.activeAccount];
  1636. // FILE -> Metadata
  1637. if (metadataNet.directory == NO) {
  1638. // move metadata
  1639. //[CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1640. [[NCManageDatabase sharedInstance] moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1641. }
  1642. // DIRECTORY -> Directory - CCMetadata
  1643. if (metadataNet.directory == YES) {
  1644. // delete all dir / subdir
  1645. NSArray *directoryIDs = [CCCoreData deleteDirectoryAndSubDirectory:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName] activeAccount:app.activeAccount];
  1646. // delete all metadata and local file in dir / subdir
  1647. for (NSString *directoryIDDelete in directoryIDs) {
  1648. //[CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(directoryID == %@)AND (account == %@)",directoryIDDelete, app.activeAccount]];
  1649. [[NCManageDatabase sharedInstance] deleteMetadata:[NSPredicate predicateWithFormat:@"(directoryID == %@)AND (account == %@)",directoryIDDelete, app.activeAccount]];
  1650. }
  1651. // move metadata
  1652. //[CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1653. [[NCManageDatabase sharedInstance] moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1654. // Add new directory
  1655. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1656. [CCCoreData addDirectory:newDirectory permissions:nil activeAccount:app.activeAccount];
  1657. // Check Offline
  1658. if ([CCCoreData isOfflineDirectoryServerUrl:serverUrlTo activeAccount:app.activeAccount])
  1659. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1660. }
  1661. // reload Datasource
  1662. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1663. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1664. else
  1665. [self reloadDatasource];
  1666. // Next file
  1667. [_selectedMetadatas removeObjectAtIndex:0];
  1668. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:metadataNet.serverUrlTo waitUntilDone:NO];
  1669. }
  1670. }
  1671. - (void)moveFileOrFolder:(NSString *)serverUrlTo
  1672. {
  1673. if ([_selectedMetadatas count] > 0) {
  1674. tableMetadata *metadata = [_selectedMetadatas objectAtIndex:0];
  1675. // Plain
  1676. if (metadata.cryptated == NO) {
  1677. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withPassword:app.activePassword withUrl:app.activeUrl isCryptoCloudMode:NO];
  1678. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1679. if(!error) {
  1680. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1681. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1682. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1683. }];
  1684. [alert addAction:ok];
  1685. [self presentViewController:alert animated:YES completion:nil];
  1686. });
  1687. return;
  1688. }
  1689. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1690. metadataNet.action = actionMoveFileOrFolder;
  1691. metadataNet.directory = metadata.directory;
  1692. metadataNet.fileID = metadata.fileID;
  1693. metadataNet.directoryID = metadata.directoryID;
  1694. metadataNet.directoryIDTo = [CCCoreData getDirectoryIDFromServerUrl:serverUrlTo activeAccount:app.activeAccount];
  1695. metadataNet.fileName = metadata.fileName;
  1696. metadataNet.fileNamePrint = metadataNet.fileNamePrint;
  1697. metadataNet.fileNameTo = metadata.fileName;
  1698. metadataNet.rev = metadata.rev;
  1699. metadataNet.selector = selectorMove;
  1700. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1701. metadataNet.serverUrlTo = serverUrlTo;
  1702. [_queueSelector addObject:metadataNet.selector];
  1703. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1704. }
  1705. // cyptated
  1706. if (metadata.cryptated == YES) {
  1707. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1708. metadataNet.action = actionMoveFileOrFolder;
  1709. metadataNet.directory = metadata.directory;
  1710. metadataNet.fileID = metadata.fileID;
  1711. metadataNet.directoryID = metadata.directoryID;
  1712. metadataNet.directoryIDTo = [CCCoreData getDirectoryIDFromServerUrl:serverUrlTo activeAccount:app.activeAccount];
  1713. metadataNet.fileNamePrint = metadata.fileNamePrint;
  1714. metadataNet.rev = metadata.rev;
  1715. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1716. metadataNet.serverUrlTo = serverUrlTo;
  1717. // data
  1718. metadataNet.fileName = metadata.fileNameData;
  1719. metadataNet.fileNameTo = metadata.fileNameData;
  1720. metadataNet.selector = selectorMoveCrypto;
  1721. [_queueSelector addObject:metadataNet.selector];
  1722. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1723. // plist
  1724. metadataNet.fileName = metadata.fileName;
  1725. metadataNet.fileNameTo = metadata.fileName;
  1726. metadataNet.selector = selectorMovePlist;
  1727. [_queueSelector addObject:metadataNet.selector];
  1728. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1729. }
  1730. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), _numSelectedMetadatas - [_selectedMetadatas count] + 1, _numSelectedMetadatas] mode:MBProgressHUDModeIndeterminate color:nil];
  1731. }
  1732. }
  1733. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title selectedMetadatas:(NSArray *)selectedMetadatas
  1734. {
  1735. [_selectedMetadatas removeAllObjects];
  1736. [_queueSelector removeAllObjects];
  1737. _selectedMetadatas = [[NSMutableArray alloc] initWithArray:selectedMetadatas];
  1738. _numSelectedMetadatas = [_selectedMetadatas count];
  1739. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:serverUrlTo waitUntilDone:NO];
  1740. [self tableViewSelect:NO];
  1741. }
  1742. - (void)moveOpenWindow:(NSArray *)indexPaths
  1743. {
  1744. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1745. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1746. viewController.delegate = self;
  1747. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1748. viewController.selectedMetadatas = [self getMetadatasFromSelectedRows:indexPaths];
  1749. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1750. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1751. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1752. viewController.networkingOperationQueue = app.netQueue;
  1753. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1754. [self presentViewController:navigationController animated:YES completion:nil];
  1755. }
  1756. #pragma --------------------------------------------------------------------------------------------
  1757. #pragma mark ===== Create folder =====
  1758. #pragma --------------------------------------------------------------------------------------------
  1759. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1760. {
  1761. [_hud hideHud];
  1762. if (message)
  1763. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1764. }
  1765. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1766. {
  1767. [_hud hideHud];
  1768. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1769. [CCCoreData addDirectory:newDirectory permissions:nil activeAccount:app.activeAccount];
  1770. // Check Offline
  1771. if ([CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount])
  1772. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1773. // Load Folder or the Datasource
  1774. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced]) {
  1775. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1776. } else {
  1777. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1778. }
  1779. }
  1780. - (void)createFolder:(NSString *)fileNameFolder folderCameraUpload:(BOOL)folderCameraUpload
  1781. {
  1782. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1783. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1784. if (![fileNameFolder length]) return;
  1785. if (folderCameraUpload) metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPath:app.activeUrl];
  1786. else metadataNet.serverUrl = _serverUrl;
  1787. metadataNet.action = actionCreateFolder;
  1788. if (folderCameraUpload)
  1789. metadataNet.options = @"folderCameraUpload";
  1790. metadataNet.fileName = fileNameFolder;
  1791. metadataNet.selector = selectorCreateFolder;
  1792. metadataNet.selectorPost = selectorReadFolderForced;
  1793. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1794. if (!folderCameraUpload)
  1795. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1796. }
  1797. - (void)createFolderEncrypted:(NSString *)fileNameFolder
  1798. {
  1799. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1800. NSString *fileNamePlist;
  1801. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1802. if (![fileNameFolder length]) return;
  1803. NSString *title = [AESCrypt encrypt:fileNameFolder password:[[CCCrypto sharedManager] getKeyPasscode:[CCUtility getUUID]]];
  1804. fileNamePlist = [[CCCrypto sharedManager] createFilenameEncryptor:fileNameFolder uuid:[CCUtility getUUID]];
  1805. [[CCCrypto sharedManager] createFilePlist:[NSTemporaryDirectory() stringByAppendingString:fileNamePlist] title:title len:0 directory:true uuid:[CCUtility getUUID] nameCurrentDevice:[CCUtility getNameCurrentDevice] icon:@""];
  1806. // Create folder
  1807. metadataNet.action = actionCreateFolder;
  1808. metadataNet.fileName = fileNamePlist;
  1809. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1810. metadataNet.selector = selectorCreateFolder;
  1811. metadataNet.serverUrl = _serverUrl;
  1812. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1813. // upload plist file
  1814. metadataNet.action = actionUploadOnlyPlist;
  1815. metadataNet.fileName = [fileNamePlist stringByAppendingString:@".plist"];
  1816. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1817. metadataNet.selectorPost = selectorReadFolderForced;
  1818. metadataNet.serverUrl = _serverUrl;
  1819. metadataNet.session = k_upload_session_foreground;
  1820. metadataNet.taskStatus = k_taskStatusResume;
  1821. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1822. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1823. }
  1824. - (void)createFolderCameraUpload
  1825. {
  1826. NSString *cameraFolderName = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderName];
  1827. [self createFolder:cameraFolderName folderCameraUpload:YES];
  1828. }
  1829. #pragma --------------------------------------------------------------------------------------------
  1830. #pragma mark ===== Encrypted / Decrypted Folder =====
  1831. #pragma --------------------------------------------------------------------------------------------
  1832. - (void)encyptedDecryptedFolder
  1833. {
  1834. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  1835. if (_metadata.cryptated) {
  1836. // DECRYPTED
  1837. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1838. //-------------------------- RENAME -------------------------------------------//
  1839. metadataNet.action = actionMoveFileOrFolder;
  1840. metadataNet.fileID = _metadata.fileID;
  1841. metadataNet.fileName = _metadata.fileNameData;
  1842. metadataNet.fileNameTo = _metadata.fileNamePrint;
  1843. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1844. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1845. metadataNet.selector = selectorRename;
  1846. metadataNet.serverUrl = serverUrl;
  1847. metadataNet.serverUrlTo = serverUrl;
  1848. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1849. //-------------------------- DELETE -------------------------------------------//
  1850. metadataNet.action = actionDeleteFileDirectory;
  1851. metadataNet.fileID = _metadata.fileID;
  1852. metadataNet.fileName = _metadata.fileName;
  1853. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1854. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1855. metadataNet.selector = selectorDeletePlist;
  1856. metadataNet.selectorPost = selectorReadFolderForced;
  1857. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1858. } else {
  1859. // ENCRYPTED
  1860. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1861. // Create File Plist
  1862. NSString *fileNameCrypto = [[CCCrypto sharedManager] createFileDirectoryPlist:_metadata];
  1863. //-------------------------- RENAME -------------------------------------------//
  1864. metadataNet.action = actionMoveFileOrFolder;
  1865. metadataNet.fileID = _metadata.fileID;
  1866. metadataNet.fileName = _metadata.fileName;
  1867. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1868. metadataNet.fileNameTo = fileNameCrypto;
  1869. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1870. metadataNet.selector = selectorRename;
  1871. metadataNet.serverUrl = serverUrl;
  1872. metadataNet.serverUrlTo = serverUrl;
  1873. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1874. //-------------------------- UPLOAD -------------------------------------------//
  1875. metadataNet.action = actionUploadOnlyPlist;
  1876. metadataNet.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  1877. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1878. metadataNet.selectorPost = selectorReadFolderForced;
  1879. metadataNet.serverUrl = serverUrl;
  1880. metadataNet.session = k_upload_session_foreground;
  1881. metadataNet.taskStatus = k_taskStatusResume;
  1882. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1883. }
  1884. }
  1885. #pragma --------------------------------------------------------------------------------------------
  1886. #pragma mark ===== Encrypted/Decrypted File =====
  1887. #pragma --------------------------------------------------------------------------------------------
  1888. - (void)encryptedSelectedFiles
  1889. {
  1890. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1891. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1892. for (tableMetadata *metadata in selectedMetadatas) {
  1893. if (metadata.cryptated == NO && metadata.directory == NO)
  1894. [metadatas addObject:metadata];
  1895. }
  1896. if ([metadatas count] > 0) {
  1897. NSLog(@"[LOG] Start encrypted selected files ...");
  1898. for (tableMetadata* metadata in metadatas) {
  1899. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1900. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorEncryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1901. }
  1902. }
  1903. [self tableViewSelect:NO];
  1904. }
  1905. - (void)decryptedSelectedFiles
  1906. {
  1907. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1908. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1909. for (tableMetadata *metadata in selectedMetadatas) {
  1910. if (metadata.cryptated == YES && metadata.directory == NO && [metadata.model length] == 0)
  1911. [metadatas addObject:metadata];
  1912. }
  1913. if ([metadatas count] > 0) {
  1914. NSLog(@"[LOG] Start decrypted selected files ...");
  1915. for (tableMetadata* metadata in metadatas) {
  1916. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1917. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDecryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1918. }
  1919. }
  1920. [self tableViewSelect:NO];
  1921. }
  1922. - (void)cmdEncryptedDecryptedFile
  1923. {
  1924. NSString *selector;
  1925. if (_metadata.cryptated == YES) selector = selectorDecryptFile;
  1926. if (_metadata.cryptated == NO) selector = selectorEncryptFile;
  1927. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  1928. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1929. }
  1930. - (void)encryptedFile:(tableMetadata *)metadata
  1931. {
  1932. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1933. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1934. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1935. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1936. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:app.activeAccount];
  1937. dispatch_async(dispatch_get_main_queue(), ^{
  1938. [[CCNetworking sharedNetworking] uploadFile:metadata.fileName serverUrl:serverUrl cryptated:YES onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1939. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1940. });
  1941. } else {
  1942. [app messageNotification:@"_encrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1943. }
  1944. }
  1945. - (void)decryptedFile:(tableMetadata *)metadata
  1946. {
  1947. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1948. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1949. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1950. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1951. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:app.activeAccount];
  1952. dispatch_async(dispatch_get_main_queue(), ^{
  1953. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:serverUrl cryptated:NO onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  1954. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1955. });
  1956. } else {
  1957. [app messageNotification:@"_decrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1958. }
  1959. }
  1960. #pragma --------------------------------------------------------------------------------------------
  1961. #pragma mark ===== Progress & Task Button =====
  1962. #pragma --------------------------------------------------------------------------------------------
  1963. - (void)triggerProgressTask:(NSNotification *)notification
  1964. {
  1965. NSDictionary *dict = notification.userInfo;
  1966. NSString *fileID = [dict valueForKey:@"fileID"];
  1967. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1968. BOOL cryptated = [[dict valueForKey:@"cryptated"] boolValue];
  1969. float progress = [[dict valueForKey:@"progress"] floatValue];
  1970. // Check
  1971. if (!fileID)
  1972. return;
  1973. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1974. if (![serverUrl isEqualToString:_serverUrl])
  1975. return;
  1976. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1977. if (indexPath) {
  1978. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1979. if (cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  1980. else cell.progressView.progressTintColor = [UIColor blackColor];
  1981. cell.progressView.hidden = NO;
  1982. [cell.progressView setProgress:progress];
  1983. }
  1984. if (progress == 0)
  1985. [self.navigationController cancelCCProgress];
  1986. else
  1987. [self.navigationController setCCProgressPercentage:progress*100 andTintColor: [NCBrandColor sharedInstance].navigationBarProgress];
  1988. }
  1989. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1990. {
  1991. UITouch * touch = [[event allTouches] anyObject];
  1992. CGPoint location = [touch locationInView:self.tableView];
  1993. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1994. if (indexPath) {
  1995. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1996. if (metadata)
  1997. [self reloadTaskButton:metadata];
  1998. }
  1999. }
  2000. - (void)reloadTaskButton:(tableMetadata *)metadata
  2001. {
  2002. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2003. __block NSURLSessionTask *findTask;
  2004. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2005. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2006. NSString *fileID = metadata.fileID;
  2007. // DOWNLOAD
  2008. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2009. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2010. for (NSURLSessionUploadTask *task in downloadTasks)
  2011. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2012. findTask = task;
  2013. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  2014. [task cancel];
  2015. }
  2016. if (!findTask) {
  2017. dispatch_async(dispatch_get_main_queue(), ^{
  2018. [app.listChangeTask setObject:@"reloadDownload" forKey:metadata.fileID];
  2019. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2020. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2021. });
  2022. }
  2023. }];
  2024. }
  2025. // UPLOAD
  2026. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2027. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2028. for (NSURLSessionUploadTask *task in uploadTasks)
  2029. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2030. findTask = task;
  2031. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2032. [task cancel];
  2033. }
  2034. if (!findTask) {
  2035. dispatch_async(dispatch_get_main_queue(), ^{
  2036. [app.listChangeTask setObject:@"reloadUpload" forKey:metadata.fileID];
  2037. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2038. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2039. });
  2040. }
  2041. }];
  2042. }
  2043. }
  2044. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  2045. {
  2046. UITouch * touch = [[event allTouches] anyObject];
  2047. CGPoint location = [touch locationInView:self.tableView];
  2048. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2049. if (indexPath) {
  2050. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2051. if (metadata)
  2052. [self cancelTaskButton:metadata reloadTable:YES];
  2053. }
  2054. }
  2055. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  2056. {
  2057. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2058. __block NSURLSessionTask *findTask;
  2059. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2060. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2061. NSString *fileID = metadata.fileID;
  2062. // DOWNLOAD
  2063. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2064. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2065. for (NSURLSessionTask *task in downloadTasks)
  2066. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2067. findTask = task;
  2068. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2069. [task cancel];
  2070. }
  2071. if (!findTask) {
  2072. dispatch_async(dispatch_get_main_queue(), ^{
  2073. [app.listChangeTask setObject:@"cancelDownload" forKey:metadata.fileID];
  2074. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2075. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2076. });
  2077. }
  2078. }];
  2079. }
  2080. // UPLOAD
  2081. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2082. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2083. for (NSURLSessionUploadTask *task in uploadTasks)
  2084. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2085. findTask = task;
  2086. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2087. [task cancel];
  2088. }
  2089. if (!findTask) {
  2090. dispatch_async(dispatch_get_main_queue(), ^{
  2091. [app.listChangeTask setObject:@"cancelUpload" forKey:metadata.fileID];
  2092. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2093. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2094. });
  2095. }
  2096. }];
  2097. }
  2098. }
  2099. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  2100. {
  2101. UITouch * touch = [[event allTouches] anyObject];
  2102. CGPoint location = [touch locationInView:self.tableView];
  2103. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2104. if (indexPath) {
  2105. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2106. if (metadata)
  2107. [self stopTaskButton:metadata];
  2108. }
  2109. }
  2110. - (void)stopTaskButton:(tableMetadata *)metadata
  2111. {
  2112. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2113. __block NSURLSessionTask *findTask;
  2114. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2115. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2116. NSString *fileID = metadata.fileID;
  2117. // UPLOAD
  2118. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2119. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2120. for (NSURLSessionUploadTask *task in uploadTasks)
  2121. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2122. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2123. findTask = task;
  2124. [task cancel];
  2125. }
  2126. if (!findTask) {
  2127. dispatch_async(dispatch_get_main_queue(), ^{
  2128. [app.listChangeTask setObject:@"stopUpload" forKey:metadata.fileID];
  2129. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2130. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2131. });
  2132. }
  2133. }];
  2134. }
  2135. }
  2136. #pragma --------------------------------------------------------------------------------------------
  2137. #pragma mark ===== Shared =====
  2138. #pragma --------------------------------------------------------------------------------------------
  2139. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  2140. {
  2141. [_hud hideHud];
  2142. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2143. // change account ?
  2144. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  2145. if([record.account isEqualToString:metadataNet.account] == NO)
  2146. return;
  2147. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  2148. if (result) {
  2149. appDelegate.sharesLink = result[0];
  2150. appDelegate.sharesUserAndGroup = result[1];
  2151. }
  2152. if (openWindow) {
  2153. if (_shareOC) {
  2154. [_shareOC reloadData];
  2155. } else {
  2156. //tableMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount] context:nil];
  2157. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount]];
  2158. // Apriamo la view
  2159. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  2160. _shareOC.delegate = self;
  2161. _shareOC.metadata = metadata;
  2162. _shareOC.serverUrl = metadataNet.serverUrl;
  2163. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  2164. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  2165. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  2166. [self presentViewController:_shareOC animated:YES completion:nil];
  2167. }
  2168. }
  2169. [self tableViewReload];
  2170. }
  2171. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2172. {
  2173. [_hud hideHud];
  2174. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2175. if (_shareOC)
  2176. [_shareOC reloadData];
  2177. [self tableViewReload];
  2178. if (errorCode == 401)
  2179. [self changePasswordAccount];
  2180. }
  2181. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2182. {
  2183. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2184. metadataNet.action = actionShare;
  2185. metadataNet.fileID = metadata.fileID;
  2186. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2187. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2188. metadataNet.password = password;
  2189. metadataNet.selector = selectorShare;
  2190. metadataNet.serverUrl = serverUrl;
  2191. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2192. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2193. }
  2194. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2195. {
  2196. [_hud hideHud];
  2197. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2198. // rimuoviamo la condivisione da db
  2199. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  2200. if (result) {
  2201. appDelegate.sharesLink = result[0];
  2202. appDelegate.sharesUserAndGroup = result[1];
  2203. }
  2204. if (_shareOC)
  2205. [_shareOC reloadData];
  2206. [self tableViewReload];
  2207. }
  2208. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  2209. {
  2210. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2211. metadataNet.action = actionUnShare;
  2212. metadataNet.fileID = metadata.fileID;
  2213. metadataNet.fileName = metadata.fileName;
  2214. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2215. metadataNet.selector = selectorUnshare;
  2216. metadataNet.serverUrl = serverUrl;
  2217. metadataNet.share = share;
  2218. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2219. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2220. }
  2221. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2222. {
  2223. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2224. metadataNet.action = actionUpdateShare;
  2225. metadataNet.fileID = metadata.fileID;
  2226. metadataNet.expirationTime = expirationTime;
  2227. metadataNet.password = password;
  2228. metadataNet.selector = selectorUpdateShare;
  2229. metadataNet.serverUrl = serverUrl;
  2230. metadataNet.share = share;
  2231. metadataNet.sharePermission = permission;
  2232. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2233. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2234. }
  2235. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2236. {
  2237. [_hud hideHud];
  2238. if (_shareOC)
  2239. [_shareOC reloadUserAndGroup:items];
  2240. }
  2241. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2242. {
  2243. [_hud hideHud];
  2244. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2245. }
  2246. - (void)getUserAndGroup:(NSString *)find
  2247. {
  2248. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2249. metadataNet.action = actionGetUserAndGroup;
  2250. metadataNet.options = find;
  2251. metadataNet.selector = selectorGetUserAndGroup;
  2252. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2253. [_hud visibleIndeterminateHud];
  2254. }
  2255. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2256. {
  2257. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2258. metadataNet.action = actionShareWith;
  2259. metadataNet.fileID = metadata.fileID;
  2260. metadataNet.directoryID = directoryID;
  2261. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2262. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2263. metadataNet.serverUrl = serverUrl;
  2264. metadataNet.selector = selectorShare;
  2265. metadataNet.share = user;
  2266. metadataNet.shareeType = shareeType;
  2267. metadataNet.sharePermission = permission;
  2268. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2269. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2270. }
  2271. - (void)openWindowShare:(tableMetadata *)metadata
  2272. {
  2273. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2274. metadataNet.action = actionReadShareServer;
  2275. metadataNet.fileID = metadata.fileID;
  2276. metadataNet.fileName = metadata.fileName;
  2277. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2278. metadataNet.selector = selectorOpenWindowShare;
  2279. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2280. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2281. [_hud visibleIndeterminateHud];
  2282. }
  2283. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2284. {
  2285. CGPoint location = [tapGesture locationInView:self.tableView];
  2286. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2287. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2288. if (metadata)
  2289. [self openWindowShare:metadata];
  2290. }
  2291. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2292. {
  2293. CGPoint location = [tapGesture locationInView:self.tableView];
  2294. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2295. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2296. if (metadata) {
  2297. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2298. vc.metadata = metadata;
  2299. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2300. [self presentViewController:vc animated:YES completion:nil];
  2301. }
  2302. }
  2303. #pragma --------------------------------------------------------------------------------------------
  2304. #pragma mark ===== Favorite =====
  2305. #pragma --------------------------------------------------------------------------------------------
  2306. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2307. {
  2308. //[CCCoreData setMetadataFavoriteFileID:metadataNet.fileID favorite:[metadataNet.options boolValue] activeAccount:app.activeAccount context:nil];
  2309. _dateReadDataSource = nil;
  2310. [[NCManageDatabase sharedInstance] setMetadataFavorite:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2311. if (_isSearchMode)
  2312. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  2313. else
  2314. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  2315. //tableMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount] context:nil];
  2316. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount]];
  2317. if (metadata.directory && metadata.favorite) {
  2318. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileNameData];
  2319. [[CCSynchronize sharedSynchronize] addFavoriteFolder:dir];
  2320. }
  2321. }
  2322. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2323. {
  2324. }
  2325. - (void)addFavorite:(tableMetadata *)metadata
  2326. {
  2327. if (metadata.directory) {
  2328. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2329. } else {
  2330. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2331. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2332. }
  2333. }
  2334. - (void)removeFavorite:(tableMetadata *)metadata
  2335. {
  2336. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2337. }
  2338. #pragma --------------------------------------------------------------------------------------------
  2339. #pragma mark ===== Offline =====
  2340. #pragma --------------------------------------------------------------------------------------------
  2341. - (void)addOffline:(tableMetadata *)metadata
  2342. {
  2343. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2344. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddOffline selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2345. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2346. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2347. }
  2348. - (void)removeOffline:(tableMetadata *)metadata
  2349. {
  2350. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:NO activeAccount:app.activeAccount];
  2351. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2352. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2353. }
  2354. #pragma --------------------------------------------------------------------------------------------
  2355. #pragma mark ===== Local =====
  2356. #pragma --------------------------------------------------------------------------------------------
  2357. - (void)addLocal:(tableMetadata *)metadata
  2358. {
  2359. if (metadata.errorPasscode || !metadata.uuid) return;
  2360. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2361. if ([metadata.type isEqualToString: k_metadataType_file])
  2362. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddLocal selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2363. if ([metadata.type isEqualToString: k_metadataType_template]) {
  2364. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileName]];
  2365. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  2366. }
  2367. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2368. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2369. }
  2370. #pragma --------------------------------------------------------------------------------------------
  2371. #pragma mark ===== Open in... =====
  2372. #pragma --------------------------------------------------------------------------------------------
  2373. - (void)openIn:(tableMetadata *)metadata
  2374. {
  2375. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2376. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2377. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2378. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2379. }
  2380. #pragma --------------------------------------------------------------------------------------------
  2381. #pragma mark ===== Remove Local File =====
  2382. #pragma --------------------------------------------------------------------------------------------
  2383. - (void)removeLocalFile:(tableMetadata *)metadata
  2384. {
  2385. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2386. [CCCoreData deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (fileID == %@)", app.activeAccount, metadata.fileID]];
  2387. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2388. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:nil];
  2389. }
  2390. #pragma --------------------------------------------------------------------------------------------
  2391. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2392. #pragma --------------------------------------------------------------------------------------------
  2393. - (void)orderTable:(NSString *)order
  2394. {
  2395. [CCUtility setOrderSettings:order];
  2396. // Clear data-read of DataSource
  2397. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2398. }
  2399. - (void)ascendingTable:(BOOL)ascending
  2400. {
  2401. [CCUtility setAscendingSettings:ascending];
  2402. // Clear data-read of DataSource
  2403. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2404. }
  2405. - (void)directoryOnTop:(BOOL)directoryOnTop
  2406. {
  2407. [CCUtility setDirectoryOnTop:directoryOnTop];
  2408. // Clear data-read of DataSource
  2409. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2410. }
  2411. - (void)tableGroupBy:(NSString *)groupBy
  2412. {
  2413. [CCUtility setGroupBySettings:groupBy];
  2414. // Clear data-read of DataSource
  2415. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2416. }
  2417. #pragma --------------------------------------------------------------------------------------------
  2418. #pragma mark ==== Menu LOGO ====
  2419. #pragma --------------------------------------------------------------------------------------------
  2420. - (void)menuLogo
  2421. {
  2422. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2423. return;
  2424. // Brand
  2425. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2426. return;
  2427. if ([app.netQueue operationCount] > 0 || [app.netQueueDownload operationCount] > 0 || [app.netQueueDownloadWWan operationCount] > 0 || [app.netQueueUpload operationCount] > 0 || [app.netQueueUploadWWan operationCount] > 0 || [[NCManageDatabase sharedInstance] countAutomaticUpload:nil] > 0) {
  2428. [app messageNotification:@"_transfers_in_queue_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  2429. return;
  2430. }
  2431. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2432. NSMutableArray *menuArray = [NSMutableArray new];
  2433. for (NSString *account in listAccount) {
  2434. if ([account isEqualToString:app.activeAccount]) continue;
  2435. CCMenuItem *item = [[CCMenuItem alloc] init];
  2436. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2437. item.argument = account;
  2438. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2439. item.target = self;
  2440. item.action = @selector(changeDefaultAccount:);
  2441. [menuArray addObject:item];
  2442. }
  2443. if ([menuArray count] == 0)
  2444. return;
  2445. OptionalConfiguration options;
  2446. Color textColor, backgroundColor;
  2447. textColor.R = 0;
  2448. textColor.G = 0;
  2449. textColor.B = 0;
  2450. backgroundColor.R = 1;
  2451. backgroundColor.G = 1;
  2452. backgroundColor.B = 1;
  2453. NSInteger originY = 60;
  2454. options.arrowSize = 9;
  2455. options.marginXSpacing = 7;
  2456. options.marginYSpacing = 10;
  2457. options.intervalSpacing = 20;
  2458. options.menuCornerRadius = 6.5;
  2459. options.maskToBackground = NO;
  2460. options.shadowOfMenu = YES;
  2461. options.hasSeperatorLine = YES;
  2462. options.seperatorLineHasInsets = YES;
  2463. options.textColor = textColor;
  2464. options.menuBackgroundColor = backgroundColor;
  2465. CGRect rect = self.view.frame;
  2466. rect.origin.y = rect.origin.y + originY;
  2467. rect.size.height = rect.size.height - originY;
  2468. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2469. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2470. }
  2471. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2472. {
  2473. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2474. // STOP, erase all in queue networking
  2475. [app cancelAllOperations];
  2476. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:k_taskStatusCancel activeAccount:app.activeAccount activeUser:app.activeUser activeUrl:app.activeUrl];
  2477. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2478. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2479. if (tableAccount)
  2480. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password];
  2481. // go to home sweet home
  2482. [[NSNotificationCenter defaultCenter] postNotificationName:@"initializeMain" object:nil];
  2483. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2484. });
  2485. }
  2486. #pragma --------------------------------------------------------------------------------------------
  2487. #pragma mark ==== ReMenu ====
  2488. #pragma --------------------------------------------------------------------------------------------
  2489. - (void)createReMenuBackgroundView:(REMenu *)menu
  2490. {
  2491. __block CGFloat navigationBarH = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
  2492. _reMenuBackgroundView.frame = CGRectMake(0, navigationBarH, self.view.frame.size.width, self.view.frame.size.height);
  2493. [UIView animateWithDuration:0.2 animations:^{
  2494. float height = (self.view.frame.size.height + navigationBarH) - (menu.menuView.frame.size.height - self.navigationController.navigationBar.frame.size.height + 3);
  2495. if (height < self.tabBarController.tabBar.frame.size.height)
  2496. height = self.tabBarController.tabBar.frame.size.height;
  2497. _reMenuBackgroundView.frame = CGRectMake(0, self.view.frame.size.height + navigationBarH, self.view.frame.size.width, - height);
  2498. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2499. }];
  2500. }
  2501. - (void)createReMainMenu
  2502. {
  2503. NSString *ordinamento;
  2504. NSString *groupBy = _directoryGroupBy;
  2505. __block NSString *nuovoOrdinamento;
  2506. NSString *titoloNuovo, *titoloAttuale;
  2507. BOOL ascendente;
  2508. __block BOOL nuovoAscendente;
  2509. UIImage *image;
  2510. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2511. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2512. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2513. [self tableViewSelect:YES];
  2514. }
  2515. }];
  2516. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2517. ordinamento = _directoryOrder;
  2518. if ([ordinamento isEqualToString:@"fileName"]) {
  2519. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2520. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2521. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2522. nuovoOrdinamento = @"fileDate";
  2523. }
  2524. if ([ordinamento isEqualToString:@"fileDate"]) {
  2525. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2526. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2527. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2528. nuovoOrdinamento = @"fileName";
  2529. }
  2530. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2531. [self orderTable:nuovoOrdinamento];
  2532. }];
  2533. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2534. ascendente = [CCUtility getAscendingSettings];
  2535. if (ascendente) {
  2536. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2537. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2538. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2539. nuovoAscendente = false;
  2540. }
  2541. if (!ascendente) {
  2542. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2543. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2544. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2545. nuovoAscendente = true;
  2546. }
  2547. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2548. [self ascendingTable:nuovoAscendente];
  2549. }];
  2550. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2551. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2552. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2553. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2554. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2555. else [self tableGroupBy:@"alphabetic"];
  2556. }];
  2557. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2558. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2559. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2560. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2561. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2562. else [self tableGroupBy:@"typefile"];
  2563. }];
  2564. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2565. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2566. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2567. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2568. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2569. else [self tableGroupBy:@"date"];
  2570. }];
  2571. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2572. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2573. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2574. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2575. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2576. else [self directoryOnTop:YES];
  2577. }];
  2578. // REMENU --------------------------------------------------------------------------------------------------------------
  2579. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2580. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2581. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2582. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2583. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2584. app.reMainMenu.separatorHeight = 0.5;
  2585. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2586. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2587. app.reMainMenu.textColor = [UIColor blackColor];
  2588. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2589. app.reMainMenu.textShadowColor = nil;
  2590. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2591. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2592. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2593. app.reMainMenu.highlightedSeparatorColor = nil;
  2594. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2595. app.reMainMenu.highlightedTextShadowColor = nil;
  2596. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2597. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2598. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2599. app.reMainMenu.subtitleTextShadowColor = nil;
  2600. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2601. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2602. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2603. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2604. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2605. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2606. app.reMainMenu.borderWidth = 0.3;
  2607. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2608. app.reMainMenu.animationDuration = 0.2;
  2609. app.reMainMenu.closeAnimationDuration = 0.2;
  2610. app.reMainMenu.bounce = NO;
  2611. [app.reMainMenu setClosePreparationBlock:^{
  2612. // Backgroun reMenu (Gesture)
  2613. [_reMenuBackgroundView removeFromSuperview];
  2614. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2615. }];
  2616. }
  2617. - (void)toggleReMainMenu
  2618. {
  2619. if (app.reMainMenu.isOpen) {
  2620. [app.reMainMenu close];
  2621. } else {
  2622. [self createReMainMenu];
  2623. [app.reMainMenu showFromNavigationController:self.navigationController];
  2624. // Backgroun reMenu & (Gesture)
  2625. [self createReMenuBackgroundView:app.reMainMenu];
  2626. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2627. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2628. }
  2629. }
  2630. - (void)createReSelectMenu
  2631. {
  2632. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2633. app.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"deleteSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2634. [self deleteSelectionFile];
  2635. }];
  2636. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2637. app.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"moveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2638. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2639. }];
  2640. if (app.isCryptoCloudMode) {
  2641. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2642. app.encryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_encrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"encryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2643. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2644. }];
  2645. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2646. app.decryptItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_decrypted_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"decryptedSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2647. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2648. }];
  2649. }
  2650. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2651. app.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2652. [self downloadSelectedFiles];
  2653. }];
  2654. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2655. app.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2656. [self saveSelectedFiles];
  2657. }];
  2658. // REMENU --------------------------------------------------------------------------------------------------------------
  2659. if (app.isCryptoCloudMode) {
  2660. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2661. } else {
  2662. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2663. }
  2664. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2665. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2666. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2667. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2668. app.reSelectMenu.separatorHeight = 0.5;
  2669. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2670. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2671. app.reSelectMenu.textColor = [UIColor blackColor];
  2672. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2673. app.reSelectMenu.textShadowColor = nil;
  2674. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2675. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2676. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2677. app.reSelectMenu.highlightedSeparatorColor = nil;
  2678. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2679. app.reSelectMenu.highlightedTextShadowColor = nil;
  2680. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2681. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2682. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2683. app.reSelectMenu.subtitleTextShadowColor = nil;
  2684. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2685. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2686. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2687. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2688. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2689. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2690. app.reSelectMenu.borderWidth = 0.3;
  2691. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2692. app.reSelectMenu.closeAnimationDuration = 0.2;
  2693. app.reSelectMenu.animationDuration = 0.2;
  2694. app.reSelectMenu.bounce = NO;
  2695. [app.reSelectMenu setClosePreparationBlock:^{
  2696. // Backgroun reMenu (Gesture)
  2697. [_reMenuBackgroundView removeFromSuperview];
  2698. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2699. }];
  2700. }
  2701. - (void)toggleReSelectMenu
  2702. {
  2703. if (app.reSelectMenu.isOpen) {
  2704. [app.reSelectMenu close];
  2705. } else {
  2706. [self createReSelectMenu];
  2707. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2708. // Backgroun reMenu & (Gesture)
  2709. [self createReMenuBackgroundView:app.reSelectMenu];
  2710. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2711. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2712. }
  2713. }
  2714. #pragma --------------------------------------------------------------------------------------------
  2715. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2716. #pragma --------------------------------------------------------------------------------------------
  2717. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2718. {
  2719. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2720. UITableView *tableView = (UITableView*)self.view;
  2721. CGPoint touchPoint = [recognizer locationInView:self.view];
  2722. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2723. if (indexPath)
  2724. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2725. else
  2726. _metadata = nil;
  2727. [self becomeFirstResponder];
  2728. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2729. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2730. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2731. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2732. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2733. UIMenuItem *pasteFileEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_encrypted_", nil) action:@selector(pasteFileEncrypted:)];
  2734. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2735. UIMenuItem *pasteFilesEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_encrypted_", nil) action:@selector(pasteFilesEncrypted:)];
  2736. if (app.isCryptoCloudMode)
  2737. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, pasteFileEncryptedItem, pasteFilesEncryptedItem, nil]];
  2738. else
  2739. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2740. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2741. [menuController setMenuVisible:YES animated:YES];
  2742. }
  2743. }
  2744. - (BOOL)canBecomeFirstResponder
  2745. {
  2746. return YES;
  2747. }
  2748. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2749. {
  2750. // For copy file, copy files, Open in ... :
  2751. //
  2752. // NO Directory
  2753. // NO Error Passcode
  2754. // NO In Session mode (download/upload)
  2755. // NO Template
  2756. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2757. if (_isSelectedMode == NO && _metadata && !_metadata.directory && !_metadata.errorPasscode && [_metadata.session length] == 0 && ![_metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2758. // NO Cryptated with Title lenght = 0
  2759. if (!_metadata.cryptated || (_metadata.cryptated && _metadata.title.length > 0))
  2760. return YES;
  2761. }
  2762. return NO;
  2763. }
  2764. if (@selector(copyFiles:) == action) {
  2765. if (_isSelectedMode) {
  2766. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2767. for (tableMetadata *metadata in selectedMetadatas) {
  2768. if (!metadata.directory && !metadata.errorPasscode && metadata.session.length == 0 && ![metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2769. // NO Cryptated with Title lenght = 0
  2770. if (!metadata.cryptated || (metadata.cryptated && metadata.title.length > 0))
  2771. return YES;
  2772. }
  2773. }
  2774. }
  2775. return NO;
  2776. }
  2777. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2778. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2779. NSArray *items = [pasteboard items];
  2780. if ([items count] == 1) {
  2781. // Value : (NSData) metadata
  2782. NSDictionary *dic = [items objectAtIndex:0];
  2783. NSData *dataMetadata = [dic objectForKey: k_metadataKeyedUnarchiver];
  2784. tableMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2785. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2786. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2787. if (directoryUser) {
  2788. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2789. return YES;
  2790. }
  2791. return NO;
  2792. } else return NO;
  2793. }
  2794. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2795. BOOL isValid = NO;
  2796. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2797. NSArray *items = [pasteboard items];
  2798. if ([items count] <= 1) return NO;
  2799. for (NSDictionary *dic in items) {
  2800. // Value : (NSData) metadata
  2801. NSData *dataMetadata = [dic objectForKey: k_metadataKeyedUnarchiver];
  2802. tableMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2803. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2804. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2805. if (directoryUser) {
  2806. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2807. isValid = YES;
  2808. }
  2809. }
  2810. return isValid;
  2811. }
  2812. return NO;
  2813. }
  2814. /************************************ COPY ************************************/
  2815. - (void)copyFile:(id)sender
  2816. {
  2817. // Remove all item
  2818. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2819. pasteboard.items = [[NSArray alloc] init];
  2820. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2821. [self copyFileToPasteboard:_metadata];
  2822. } else {
  2823. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2824. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2825. }
  2826. }
  2827. - (void)copyFiles:(id)sender
  2828. {
  2829. // Remove all item
  2830. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2831. pasteboard.items = [[NSArray alloc] init];
  2832. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2833. for (tableMetadata *metadata in selectedMetadatas) {
  2834. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2835. [self copyFileToPasteboard:metadata];
  2836. } else {
  2837. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2838. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2839. }
  2840. }
  2841. [self tableViewSelect:NO];
  2842. }
  2843. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2844. {
  2845. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2846. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2847. // Value : (NSData) metadata
  2848. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata], k_metadataKeyedUnarchiver,nil];
  2849. [items addObject:item];
  2850. [pasteboard setItems:items];
  2851. }
  2852. /************************************ OPEN IN ... ************************************/
  2853. - (void)openinFile:(id)sender
  2854. {
  2855. [self openIn:_metadata];
  2856. }
  2857. /************************************ PASTE ************************************/
  2858. - (void)pasteFile:(id)sender
  2859. {
  2860. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2861. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2862. }
  2863. - (void)pasteFileEncrypted:(id)sender
  2864. {
  2865. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2866. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2867. }
  2868. - (void)pasteFiles:(id)sender
  2869. {
  2870. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2871. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2872. }
  2873. - (void)pasteFilesEncrypted:(id)sender
  2874. {
  2875. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2876. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2877. }
  2878. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2879. {
  2880. for (NSDictionary *dic in items) {
  2881. // Value : (NSData) metadata
  2882. NSData *dataMetadata = [dic objectForKey: k_metadataKeyedUnarchiver];
  2883. tableMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2884. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2885. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2886. if (directoryUser) {
  2887. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]]) {
  2888. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint]];
  2889. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNamePrint serverUrl:_serverUrl cryptated:cryptated onlyPlist:NO session:k_upload_session taskStatus:k_taskStatusResume selector:nil selectorPost:nil errorCode:0 delegate:nil];
  2890. }
  2891. }
  2892. }
  2893. }
  2894. #pragma --------------------------------------------------------------------------------------------
  2895. #pragma mark ===== Lock Passcode =====
  2896. #pragma --------------------------------------------------------------------------------------------
  2897. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2898. {
  2899. return _failedAttempts;
  2900. }
  2901. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2902. {
  2903. return _lockUntilDate;
  2904. }
  2905. - (void)passcodeViewCloseButtonPressed:(id)sender
  2906. {
  2907. [self dismissViewControllerAnimated:YES completion:nil];
  2908. }
  2909. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2910. {
  2911. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2912. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2913. _lockUntilDate = nil;
  2914. _failedAttempts = 0;
  2915. aResultHandler(YES);
  2916. } else aResultHandler(NO);
  2917. } else aResultHandler(YES);
  2918. }
  2919. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2920. {
  2921. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2922. switch (aViewController.type) {
  2923. case BKPasscodeViewControllerCheckPasscodeType: {
  2924. if (aViewController.fromType == CCBKPasscodeFromPasscode) {
  2925. // verifichiamo se il passcode è corretto per il seguente file -> UUID
  2926. if ([[CCCrypto sharedManager] verifyPasscode:aPasscode uuid:_metadata.uuid text:_metadata.title]) {
  2927. // scriviamo il passcode
  2928. [CCUtility setKeyChainPasscodeForUUID:_metadata.uuid conPasscode:aPasscode];
  2929. [self readFolderWithForced:YES serverUrl:_serverUrl];
  2930. } else {
  2931. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2932. [alertView show];
  2933. }
  2934. }
  2935. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2936. // possiamo procedere alla prossima directory
  2937. [self performSegueDirectoryWithControlPasscode:false];
  2938. // avviamo la sessione Passcode Lock con now
  2939. app.sessionePasscodeLock = [NSDate date];
  2940. }
  2941. // disattivazione lock cartella
  2942. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2943. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2944. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2945. if ([CCCoreData setDirectoryUnLock:lockServerUrl activeAccount:app.activeAccount] == NO) {
  2946. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2947. }
  2948. [self.tableView reloadData];
  2949. }
  2950. }
  2951. break;
  2952. default:
  2953. break;
  2954. }
  2955. }
  2956. - (void)comandoLockPassword
  2957. {
  2958. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2959. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2960. // se non è abilitato il Lock Passcode esci
  2961. if ([[CCUtility getBlockCode] length] == 0) {
  2962. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2963. [alertView show];
  2964. return;
  2965. }
  2966. // se è richiesta la disattivazione si chiede la password
  2967. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2968. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2969. viewController.delegate = self;
  2970. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2971. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2972. viewController.inputViewTitlePassword = YES;
  2973. if ([CCUtility getSimplyBlockCode]) {
  2974. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2975. viewController.passcodeInputView.maximumLength = 6;
  2976. } else {
  2977. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2978. viewController.passcodeInputView.maximumLength = 64;
  2979. }
  2980. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2981. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2982. viewController.touchIDManager = touchIDManager;
  2983. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2984. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2985. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  2986. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2987. [self presentViewController:navigationController animated:YES completion:nil];
  2988. return;
  2989. }
  2990. // ---------------- ACTIVATE PASSWORD
  2991. if([CCCoreData setDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2992. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2993. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2994. } else {
  2995. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2996. }
  2997. }
  2998. #pragma mark -
  2999. #pragma --------------------------------------------------------------------------------------------
  3000. #pragma mark ===== Swipe Tablet -> menu =====
  3001. #pragma --------------------------------------------------------------------------------------------
  3002. // more
  3003. - (NSString *)tableView:(UITableView *)tableView titleForSwipeAccessoryButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
  3004. return NSLocalizedString(@"_more_", nil);
  3005. }
  3006. - (void)tableView:(UITableView *)tableView swipeAccessoryButtonPushedForRowAtIndexPath:(NSIndexPath *)indexPath
  3007. {
  3008. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3009. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  3010. NSString *titoloCriptaDecripta, *titoloOffline, *titoloLock, *titleOfflineFolder, *titleFavorite;
  3011. BOOL offlineFolder = NO;
  3012. if (_metadata.cryptated) titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_decrypt_", nil)];
  3013. else titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  3014. if ([CCCoreData isOfflineLocalFileID:_metadata.fileID activeAccount:app.activeAccount]) titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  3015. else titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  3016. NSString *offlineServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3017. if (_metadata.directory && [CCCoreData isOfflineDirectoryServerUrl:offlineServerUrl activeAccount:app.activeAccount]) {
  3018. titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  3019. offlineFolder = YES;
  3020. } else titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  3021. if (_metadata.favorite) {
  3022. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  3023. } else {
  3024. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  3025. }
  3026. if (_metadata.directory) {
  3027. // calcolo lockServerUrl
  3028. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3029. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  3030. else titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  3031. }
  3032. TableLocalFile *recordLocalFile = [CCCoreData getLocalFileWithFileID:_metadata.fileID activeAccount:app.activeAccount];
  3033. /******************************************* AHKActionSheet *******************************************/
  3034. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.view title:nil];
  3035. actionSheet.animationDuration = 0.2;
  3036. actionSheet.blurRadius = 0.0f;
  3037. actionSheet.blurTintColor = [UIColor colorWithWhite:0.0f alpha:0.50f];
  3038. actionSheet.buttonHeight = 50.0;
  3039. actionSheet.cancelButtonHeight = 50.0f;
  3040. actionSheet.separatorHeight = 5.0f;
  3041. actionSheet.automaticallyTintButtonImages = @(NO);
  3042. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  3043. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3044. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].brand };
  3045. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3046. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  3047. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  3048. /******************************************* DIRECTORY *******************************************/
  3049. if (_metadata.directory) {
  3050. BOOL lockDirectory = NO;
  3051. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3052. // Directory bloccata ?
  3053. if ([CCCoreData isDirectoryLock:dirServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3054. NSString *cameraUploadFolderName = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderName];
  3055. NSString *cameraUploadFolderPath = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPath:app.activeUrl];
  3056. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3057. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  3058. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3059. height: 50.0
  3060. type: AHKActionSheetButtonTypeDisabled
  3061. handler: nil
  3062. ];
  3063. if (!lockDirectory && !_metadata.cryptated) {
  3064. [actionSheet addButtonWithTitle:titleFavorite
  3065. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3066. backgroundColor:[UIColor whiteColor]
  3067. height: 50.0
  3068. type:AHKActionSheetButtonTypeDefault
  3069. handler:^(AHKActionSheet *as) {
  3070. // close swipe
  3071. [self setEditing:NO animated:YES];
  3072. if (_metadata.favorite)
  3073. [self removeFavorite:_metadata];
  3074. else
  3075. [self addFavorite:_metadata];
  3076. }];
  3077. }
  3078. if (_metadata.cryptated == NO && !lockDirectory) {
  3079. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3080. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3081. backgroundColor:[UIColor whiteColor]
  3082. height: 50.0
  3083. type:AHKActionSheetButtonTypeDefault
  3084. handler:^(AHKActionSheet *as) {
  3085. // close swipe
  3086. [self setEditing:NO animated:YES];
  3087. [self openWindowShare:_metadata];
  3088. }];
  3089. }
  3090. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3091. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3092. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3093. backgroundColor:[UIColor whiteColor]
  3094. height: 50.0
  3095. type:AHKActionSheetButtonTypeDefault
  3096. handler:^(AHKActionSheet *as) {
  3097. // close swipe
  3098. [self setEditing:NO animated:YES];
  3099. //chiediamo il nome del file
  3100. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3101. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3102. alertView.tag = alertRename;
  3103. UITextField *textField = [alertView textFieldAtIndex:0];
  3104. textField.text = _metadata.fileNamePrint;
  3105. [alertView show];
  3106. }];
  3107. }
  3108. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3109. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3110. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3111. backgroundColor:[UIColor whiteColor]
  3112. height: 50.0
  3113. type:AHKActionSheetButtonTypeDefault
  3114. handler:^(AHKActionSheet *as) {
  3115. // close swipe
  3116. [self setEditing:NO animated:YES];
  3117. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3118. }];
  3119. }
  3120. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && _metadata.cryptated == NO) {
  3121. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3122. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  3123. backgroundColor:[UIColor whiteColor]
  3124. height: 50.0
  3125. type:AHKActionSheetButtonTypeDefault
  3126. handler:^(AHKActionSheet *as) {
  3127. // close swipe
  3128. [self setEditing:NO animated:YES];
  3129. // Settings new folder Automatatic upload
  3130. NSString *oldPath = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPath:app.activeUrl];
  3131. [[NCManageDatabase sharedInstance] setAccountCameraUploadFolderName:_metadata.fileName];
  3132. [[NCManageDatabase sharedInstance] setAccountCameraUploadFolderPath:serverUrl activeUrl:app.activeUrl];
  3133. [CCCoreData clearDateReadAccount:app.activeAccount serverUrl:oldPath directoryID:nil];
  3134. if (app.activeAccount.length > 0 && app.activePhotosCameraUpload)
  3135. [app.activePhotosCameraUpload reloadDatasourceForced];
  3136. [self readFolderWithForced:YES serverUrl:serverUrl];
  3137. NSLog(@"[LOG] Update Folder Photo");
  3138. NSString *folderCameraUpload = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPathAndName:app.activeUrl];
  3139. if ([folderCameraUpload length] > 0)
  3140. [[CCSynchronize sharedSynchronize] readFolderServerUrl:folderCameraUpload directoryID:[CCCoreData getDirectoryIDFromServerUrl:folderCameraUpload activeAccount:app.activeAccount] selector:selectorReadFolder];
  3141. }];
  3142. }
  3143. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES)) {
  3144. [actionSheet addButtonWithTitle:titoloLock
  3145. image:[UIImage imageNamed:@"actionSheetLock"]
  3146. backgroundColor:[UIColor whiteColor]
  3147. height: 50.0
  3148. type:AHKActionSheetButtonTypeEncrypted
  3149. handler:^(AHKActionSheet *as) {
  3150. // close swipe
  3151. [self setEditing:NO animated:YES];
  3152. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3153. }];
  3154. }
  3155. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  3156. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3157. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3158. backgroundColor:[UIColor whiteColor]
  3159. height: 50.0
  3160. type:AHKActionSheetButtonTypeEncrypted
  3161. handler:^(AHKActionSheet *as) {
  3162. // close swipe
  3163. [self setEditing:NO animated:YES];
  3164. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  3165. }];
  3166. }
  3167. [actionSheet show];
  3168. }
  3169. /******************************************* FILE *******************************************/
  3170. if ([_metadata.type isEqualToString: k_metadataType_file] && !_metadata.directory) {
  3171. UIImage *iconHeader;
  3172. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3173. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3174. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3175. else
  3176. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3177. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3178. image: iconHeader
  3179. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3180. height: 50.0
  3181. type: AHKActionSheetButtonTypeDisabled
  3182. handler: nil
  3183. ];
  3184. if (!_metadata.cryptated) {
  3185. [actionSheet addButtonWithTitle:titleFavorite
  3186. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3187. backgroundColor:[UIColor whiteColor]
  3188. height: 50.0
  3189. type:AHKActionSheetButtonTypeDefault
  3190. handler:^(AHKActionSheet *as) {
  3191. // close swipe
  3192. [self setEditing:NO animated:YES];
  3193. if (_metadata.favorite)
  3194. [self removeFavorite:_metadata];
  3195. else
  3196. [self addFavorite:_metadata];
  3197. }];
  3198. }
  3199. if (_metadata.cryptated == NO) {
  3200. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3201. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3202. backgroundColor:[UIColor whiteColor]
  3203. height: 50.0
  3204. type:AHKActionSheetButtonTypeDefault
  3205. handler:^(AHKActionSheet *as) {
  3206. // close swipe
  3207. [self setEditing:NO animated:YES];
  3208. [self openWindowShare:_metadata];
  3209. }];
  3210. }
  3211. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3212. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  3213. backgroundColor:[UIColor whiteColor]
  3214. height: 50.0
  3215. type:AHKActionSheetButtonTypeDefault
  3216. handler:^(AHKActionSheet *as) {
  3217. // close swipe
  3218. [self setEditing:NO animated:YES];
  3219. [self performSelector:@selector(openIn:) withObject:_metadata];
  3220. }];
  3221. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3222. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3223. backgroundColor:[UIColor whiteColor]
  3224. height: 50.0
  3225. type:AHKActionSheetButtonTypeDefault
  3226. handler:^(AHKActionSheet *as) {
  3227. // close swipe
  3228. [self setEditing:NO animated:YES];
  3229. //chiediamo il nome del file
  3230. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3231. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3232. alertView.tag = alertRename;
  3233. UITextField *textField = [alertView textFieldAtIndex:0];
  3234. textField.text = _metadata.fileNamePrint;
  3235. [alertView show];
  3236. }];
  3237. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3238. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3239. backgroundColor:[UIColor whiteColor]
  3240. height: 50.0
  3241. type:AHKActionSheetButtonTypeDefault
  3242. handler:^(AHKActionSheet *as) {
  3243. // close swipe
  3244. [self setEditing:NO animated:YES];
  3245. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3246. }];
  3247. if (recordLocalFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3248. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3249. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3250. backgroundColor:[UIColor whiteColor]
  3251. height: 50.0
  3252. type:AHKActionSheetButtonTypeDefault
  3253. handler:^(AHKActionSheet *as) {
  3254. // close swipe
  3255. [self setEditing:NO animated:YES];
  3256. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3257. }];
  3258. }
  3259. if (app.isCryptoCloudMode) {
  3260. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3261. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3262. backgroundColor:[UIColor whiteColor]
  3263. height: 50.0
  3264. type:AHKActionSheetButtonTypeEncrypted
  3265. handler:^(AHKActionSheet *as) {
  3266. // close swipe
  3267. [self setEditing:NO animated:YES];
  3268. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3269. }];
  3270. }
  3271. [actionSheet show];
  3272. }
  3273. /******************************************* TEMPLATE *******************************************/
  3274. if ([_metadata.type isEqualToString: k_metadataType_template]) {
  3275. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3276. image: [UIImage imageNamed:_metadata.iconName]
  3277. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3278. height: 50.0
  3279. type: AHKActionSheetButtonTypeDisabled
  3280. handler: nil
  3281. ];
  3282. if ([_metadata.model isEqualToString:@"note"]) {
  3283. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3284. image:[UIImage imageNamed:@"actionSheetRename"]
  3285. backgroundColor:[UIColor whiteColor]
  3286. height: 50.0
  3287. type:AHKActionSheetButtonTypeDefault
  3288. handler:^(AHKActionSheet *as) {
  3289. // close swipe
  3290. [self setEditing:NO animated:YES];
  3291. //chiediamo il nome del file
  3292. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3293. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3294. alertView.tag = alertRename;
  3295. UITextField *textField = [alertView textFieldAtIndex:0];
  3296. textField.text = _metadata.fileNamePrint;
  3297. [alertView show];
  3298. }];
  3299. }
  3300. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3301. image:[UIImage imageNamed:@"actionSheetMove"]
  3302. backgroundColor:[UIColor whiteColor]
  3303. height: 50.0
  3304. type:AHKActionSheetButtonTypeDefault
  3305. handler:^(AHKActionSheet *as) {
  3306. // close swipe
  3307. [self setEditing:NO animated:YES];
  3308. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3309. }];
  3310. [actionSheet show];
  3311. }
  3312. }
  3313. - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
  3314. {
  3315. return NSLocalizedString(@"_delete_", nil);
  3316. }
  3317. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3318. {
  3319. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3320. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return NO;
  3321. else return YES;
  3322. }
  3323. - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  3324. {
  3325. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3326. if (metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return UITableViewCellEditingStyleNone;
  3327. else return UITableViewCellEditingStyleDelete;
  3328. }
  3329. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  3330. {
  3331. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3332. BOOL lockDirectory = NO;
  3333. // Directory locked ?
  3334. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account] addFileName:metadata.fileNameData];
  3335. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3336. if (lockDirectory && editingStyle == UITableViewCellEditingStyleDelete) {
  3337. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  3338. return;
  3339. }
  3340. if (editingStyle == UITableViewCellEditingStyleDelete) {
  3341. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3342. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  3343. style:UIAlertActionStyleDestructive
  3344. handler:^(UIAlertAction *action) {
  3345. [self performSelector:@selector(deleteFile) withObject:nil];
  3346. }]];
  3347. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  3348. style:UIAlertActionStyleCancel
  3349. handler:^(UIAlertAction *action) {
  3350. [alertController dismissViewControllerAnimated:YES completion:nil];
  3351. }]];
  3352. alertController.popoverPresentationController.sourceView = self.view;
  3353. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3354. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3355. [alertController.view layoutIfNeeded];
  3356. [self presentViewController:alertController animated:YES completion:nil];
  3357. }
  3358. }
  3359. #pragma --------------------------------------------------------------------------------------------
  3360. #pragma mark - ==== Datasource ====
  3361. #pragma --------------------------------------------------------------------------------------------
  3362. - (void)clearDateReadDataSource:(NSNotification *)notification
  3363. {
  3364. _dateReadDataSource = Nil;
  3365. [self reloadDatasource];
  3366. }
  3367. - (void)reloadDatasource
  3368. {
  3369. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  3370. }
  3371. - (void)reloadDatasource:(NSString *)serverUrl fileID:(NSString *)fileID selector:(NSString *)selector
  3372. {
  3373. // test
  3374. if (app.activeAccount.length == 0 || serverUrl.length == 0)
  3375. return;
  3376. // Search Mode
  3377. if(_isSearchMode) {
  3378. if ([selector length] == 0 || [selector isEqualToString:selectorSearch]) {
  3379. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3380. } else {
  3381. [self readFolderWithForced:NO serverUrl:serverUrl];
  3382. }
  3383. [self tableViewReload];
  3384. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3385. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3386. _noFilesSearchDescription = @"";
  3387. }
  3388. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3389. _noFilesSearchTitle = @"";
  3390. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3391. }
  3392. [self.tableView reloadEmptyDataSet];
  3393. return;
  3394. }
  3395. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3396. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3397. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  3398. [app.activeTransfers reloadDatasource];
  3399. } else {
  3400. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3401. if (main) {
  3402. [main reloadDatasource];
  3403. } else {
  3404. [self tableViewReload];
  3405. [app.activeTransfers reloadDatasource];
  3406. }
  3407. }
  3408. return;
  3409. }
  3410. // Offline folder ?
  3411. _isOfflineServerUrl = [CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount];
  3412. [app.activeTransfers reloadDatasource];
  3413. // Settaggio variabili per le ottimizzazioni
  3414. _directoryGroupBy = [CCUtility getGroupBySettings];
  3415. _directoryOrder = [CCUtility getOrderSettings];
  3416. // Controllo data lettura Data Source
  3417. NSDate *dateDateRecordDirectory = [CCCoreData getDateReadDirectoryID:[CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount] activeAccount:app.activeAccount];
  3418. dateDateRecordDirectory = nil;
  3419. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3420. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3421. _dateReadDataSource = [NSDate date];
  3422. // Data Source
  3423. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@)", app.activeAccount, [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount]] sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  3424. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3425. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3426. } else {
  3427. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3428. }
  3429. [self tableViewReload];
  3430. }
  3431. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3432. {
  3433. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3434. if (selectedRows.count > 0) {
  3435. for (NSIndexPath *selectionIndex in selectedRows) {
  3436. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3437. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3438. [metadatas addObject:metadata];
  3439. }
  3440. }
  3441. return metadatas;
  3442. }
  3443. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3444. {
  3445. NSInteger section = indexPath.section + 1;
  3446. NSInteger row = indexPath.row + 1;
  3447. NSInteger totSections =[_sectionDataSource.sections count] ;
  3448. if ((totSections < section) || (section > totSections)) {
  3449. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3450. return nil;
  3451. }
  3452. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3453. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3454. if (fileIDs) {
  3455. NSInteger totRows =[fileIDs count] ;
  3456. if ((totRows < row) || (row > totRows)) {
  3457. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3458. return nil;
  3459. }
  3460. } else {
  3461. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3462. return nil;
  3463. }
  3464. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3465. return [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3466. }
  3467. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3468. {
  3469. NSInteger totSections =[_sectionDataSource.sections count] ;
  3470. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3471. #if DEBUG
  3472. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:[NSString stringWithFormat:@"DEBUG [3] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section] delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3473. [alertView show];
  3474. #endif
  3475. return nil;
  3476. }
  3477. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3478. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3479. }
  3480. #pragma --------------------------------------------------------------------------------------------
  3481. #pragma mark - ==== Table ====
  3482. #pragma --------------------------------------------------------------------------------------------
  3483. - (void)tableViewSelect:(BOOL)edit
  3484. {
  3485. // chiudiamo eventuali swipe aperti
  3486. if (edit) [self.tableView setEditing:NO animated:NO];
  3487. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3488. [self.tableView setEditing:edit animated:YES];
  3489. _isSelectedMode = edit;
  3490. if (edit)
  3491. [self setUINavigationBarSelected];
  3492. else
  3493. [self setUINavigationBarDefault];
  3494. [self setTitle];
  3495. }
  3496. - (void)tableViewReload
  3497. {
  3498. // ricordiamoci le row selezionate
  3499. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3500. [self.tableView reloadData];
  3501. for (NSIndexPath *path in indexPaths)
  3502. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3503. [self setTableViewFooter];
  3504. if (self.tableView.editing)
  3505. [self setTitle];
  3506. }
  3507. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3508. {
  3509. return 60;
  3510. }
  3511. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3512. {
  3513. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3514. }
  3515. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3516. {
  3517. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3518. }
  3519. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3520. {
  3521. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3522. NSString *sectionTitle = [sections objectAtIndex:section];
  3523. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3524. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3525. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3526. return 20.f;
  3527. }
  3528. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3529. {
  3530. float shift;
  3531. UIVisualEffectView *visualEffectView;
  3532. // Titolo
  3533. NSString *titleSection;
  3534. // Controllo
  3535. if ([_sectionDataSource.sections count] == 0)
  3536. return nil;
  3537. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]]) titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3538. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]]) titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3539. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3540. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3541. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3542. else titleSection = NSLocalizedString(titleSection,nil);
  3543. // Formato titolo
  3544. NSString *currentDevice = [CCUtility currentDevice];
  3545. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3546. visualEffectView = [[UIVisualEffectView alloc] init];
  3547. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3548. } else {
  3549. UIVisualEffect *blurEffect;
  3550. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3551. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3552. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3553. }
  3554. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3555. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) shift = - 35;
  3556. else shift = - 20;
  3557. } else shift = - 10;
  3558. // Title
  3559. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3560. titleLabel.backgroundColor = [UIColor clearColor];
  3561. titleLabel.textColor = [UIColor blackColor];
  3562. titleLabel.font = [UIFont systemFontOfSize:12];
  3563. titleLabel.textAlignment = NSTextAlignmentLeft;
  3564. titleLabel.text = titleSection;
  3565. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3566. [visualEffectView addSubview:titleLabel];
  3567. // Elements
  3568. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3569. elementLabel.backgroundColor = [UIColor clearColor];
  3570. elementLabel.textColor = [UIColor blackColor];;
  3571. elementLabel.font = [UIFont systemFontOfSize:12];
  3572. elementLabel.textAlignment = NSTextAlignmentRight;
  3573. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3574. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3575. NSUInteger rowsCount = [metadatas count];
  3576. if (rowsCount == 0) return nil;
  3577. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3578. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3579. [visualEffectView addSubview:elementLabel];
  3580. return visualEffectView;
  3581. }
  3582. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3583. {
  3584. return [_sectionDataSource.sections indexOfObject:title];
  3585. }
  3586. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3587. {
  3588. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3589. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3590. else
  3591. return nil;
  3592. }
  3593. /*
  3594. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3595. {
  3596. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3597. }
  3598. }
  3599. */
  3600. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3601. {
  3602. NSString *typeCell;
  3603. NSString *dataFile;
  3604. NSString *lunghezzaFile;
  3605. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3606. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  3607. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3608. else typeCell = @"CellMainTransfer";
  3609. if (!metadata)
  3610. return [tableView dequeueReusableCellWithIdentifier:typeCell];
  3611. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3612. // separator
  3613. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3614. // change color selection
  3615. UIView *selectionColor = [[UIView alloc] init];
  3616. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3617. cell.selectedBackgroundView = selectionColor;
  3618. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3619. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3620. // ----------------------------------------------------------------------------------------------------------
  3621. // DEFAULT
  3622. // ----------------------------------------------------------------------------------------------------------
  3623. cell.fileImageView.image = nil;
  3624. cell.statusImageView.image = nil;
  3625. cell.offlineImageView.image = nil;
  3626. cell.synchronizedImageView.image = nil;
  3627. cell.sharedImageView.image = nil;
  3628. cell.labelTitle.enabled = YES;
  3629. cell.labelTitle.text = @"";
  3630. cell.labelInfoFile.enabled = YES;
  3631. cell.labelInfoFile.text = @"";
  3632. cell.progressView.progress = 0.0;
  3633. cell.progressView.hidden = YES;
  3634. cell.cancelTaskButton.hidden = YES;
  3635. cell.reloadTaskButton.hidden = YES;
  3636. cell.stopTaskButton.hidden = YES;
  3637. // Encrypted color
  3638. if (metadata.cryptated) {
  3639. cell.labelTitle.textColor = [NCBrandColor sharedInstance].cryptocloud;
  3640. } else {
  3641. cell.labelTitle.textColor = [UIColor blackColor];
  3642. }
  3643. // ----------------------------------------------------------------------------------------------------------
  3644. // File Name & Folder
  3645. // ----------------------------------------------------------------------------------------------------------
  3646. // nome del file
  3647. cell.labelTitle.text = metadata.fileNamePrint;
  3648. // è una directory
  3649. if (metadata.directory) {
  3650. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3651. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3652. lunghezzaFile = @" ";
  3653. // ----------------------------------------------------------------------------------------------------------
  3654. // Favorite Folder
  3655. // ----------------------------------------------------------------------------------------------------------
  3656. if (metadata.favorite) {
  3657. cell.offlineImageView.image = [UIImage imageNamed:@"favorite"];
  3658. }
  3659. } else {
  3660. // File
  3661. dataFile = [CCUtility dateDiff:metadata.date];
  3662. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3663. // Plist ancora da scaricare
  3664. if (metadata.cryptated && [metadata.title length] == 0) {
  3665. dataFile = @" ";
  3666. lunghezzaFile = @" ";
  3667. }
  3668. TableLocalFile *recordLocalFile = [CCCoreData getLocalFileWithFileID:metadata.fileID activeAccount:app.activeAccount];
  3669. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3670. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3671. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3672. if ([metadata.type isEqualToString: k_metadataType_template] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO)
  3673. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", dataFile];
  3674. if ([metadata.type isEqualToString: k_metadataType_file] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO) {
  3675. if (recordLocalFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3676. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ • %@", dataFile, lunghezzaFile];
  3677. else
  3678. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ ◦ %@", dataFile, lunghezzaFile];
  3679. }
  3680. // Plist ancora da scaricare
  3681. if ([dataFile isEqualToString:@" "] && [lunghezzaFile isEqualToString:@" "])
  3682. cell.labelInfoFile.text = NSLocalizedString(@"_no_plist_pull_down_",nil);
  3683. cell.accessoryType = UITableViewCellAccessoryNone;
  3684. }
  3685. // ----------------------------------------------------------------------------------------------------------
  3686. // File Image View
  3687. // ----------------------------------------------------------------------------------------------------------
  3688. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3689. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3690. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadata.fileID];
  3691. if (cell.fileImageView.image == nil) {
  3692. NSString *fileID = metadata.fileID;
  3693. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3694. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID]];
  3695. [app.icoImagesCache setObject:image forKey:fileID];
  3696. dispatch_async(dispatch_get_main_queue(), ^{
  3697. CCCellMainTransfer *cell = [tableView cellForRowAtIndexPath:indexPath];
  3698. if (cell)
  3699. cell.fileImageView.image = image;
  3700. });
  3701. });
  3702. }
  3703. } else {
  3704. if (metadata.directory)
  3705. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3706. else
  3707. cell.fileImageView.image = [UIImage imageNamed:metadata.iconName];
  3708. if (metadata.thumbnailExists)
  3709. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3710. }
  3711. // ----------------------------------------------------------------------------------------------------------
  3712. // Image Status cyptated & Lock Passcode
  3713. // ----------------------------------------------------------------------------------------------------------
  3714. // File Cyptated
  3715. if (metadata.cryptated && metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_template] == NO) {
  3716. cell.statusImageView.image = [UIImage imageNamed:@"lock"];
  3717. }
  3718. // Directory con passcode lock attivato
  3719. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  3720. if (metadata.directory && ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length]))
  3721. cell.statusImageView.image = [UIImage imageNamed:@"passcode"];
  3722. // ----------------------------------------------------------------------------------------------------------
  3723. // Offline
  3724. // ----------------------------------------------------------------------------------------------------------
  3725. BOOL isOfflineFile = [CCCoreData isOfflineLocalFileID:metadata.fileID activeAccount:app.activeAccount];
  3726. if (isOfflineFile) {
  3727. cell.offlineImageView.image = [UIImage imageNamed:@"offline"];
  3728. }
  3729. // ----------------------------------------------------------------------------------------------------------
  3730. // Favorite
  3731. // ----------------------------------------------------------------------------------------------------------
  3732. if (metadata.favorite) {
  3733. cell.offlineImageView.image = [UIImage imageNamed:@"favorite"];
  3734. }
  3735. // ----------------------------------------------------------------------------------------------------------
  3736. // Share
  3737. // ----------------------------------------------------------------------------------------------------------
  3738. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3739. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3740. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3741. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3742. // Aggiungiamo il Tap per le shared
  3743. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3744. if (isShare) {
  3745. if (metadata.directory) {
  3746. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3747. cell.sharedImageView.userInteractionEnabled = NO;
  3748. } else {
  3749. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3750. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3751. [tap setNumberOfTapsRequired:1];
  3752. cell.sharedImageView.userInteractionEnabled = YES;
  3753. [cell.sharedImageView addGestureRecognizer:tap];
  3754. }
  3755. }
  3756. if (isMounted) {
  3757. if (metadata.directory) {
  3758. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3759. cell.sharedImageView.userInteractionEnabled = NO;
  3760. } else {
  3761. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3762. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3763. [tap setNumberOfTapsRequired:1];
  3764. cell.sharedImageView.userInteractionEnabled = YES;
  3765. [cell.sharedImageView addGestureRecognizer:tap];
  3766. }
  3767. }
  3768. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3769. if (metadata.directory) {
  3770. if ([shareLink length] > 0)
  3771. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3772. if ([shareUserAndGroup length] > 0)
  3773. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3774. cell.sharedImageView.userInteractionEnabled = NO;
  3775. } else {
  3776. if ([shareLink length] > 0)
  3777. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3778. if ([shareUserAndGroup length] > 0)
  3779. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3780. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3781. [tap setNumberOfTapsRequired:1];
  3782. cell.sharedImageView.userInteractionEnabled = YES;
  3783. [cell.sharedImageView addGestureRecognizer:tap];
  3784. }
  3785. }
  3786. } else {
  3787. cell.sharedImageView.userInteractionEnabled = NO;
  3788. }
  3789. // ----------------------------------------------------------------------------------------------------------
  3790. // downloadFile
  3791. // ----------------------------------------------------------------------------------------------------------
  3792. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3793. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusdownloadcrypto"];
  3794. else cell.statusImageView.image = [UIImage imageNamed:@"statusdownload"];
  3795. // sessionTaskIdentifier : RELOAD + STOP
  3796. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3797. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3798. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3799. cell.cancelTaskButton.hidden = NO;
  3800. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3801. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3802. cell.reloadTaskButton.hidden = NO;
  3803. }
  3804. // sessionTaskIdentifierPlist : RELOAD
  3805. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) {
  3806. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3807. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3808. cell.reloadTaskButton.hidden = NO;
  3809. }
  3810. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3811. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3812. if (progress > 0) {
  3813. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3814. else cell.progressView.progressTintColor = [UIColor blackColor];
  3815. cell.progressView.progress = progress;
  3816. cell.progressView.hidden = NO;
  3817. }
  3818. // ----------------------------------------------------------------------------------------------------------
  3819. // downloadFile Error
  3820. // ----------------------------------------------------------------------------------------------------------
  3821. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3822. cell.statusImageView.image = [UIImage imageNamed:@"statuserror"];
  3823. if ([metadata.sessionError length] == 0)
  3824. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3825. else
  3826. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3827. }
  3828. }
  3829. // ----------------------------------------------------------------------------------------------------------
  3830. // uploadFile
  3831. // ----------------------------------------------------------------------------------------------------------
  3832. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3833. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusuploadcrypto"];
  3834. else cell.statusImageView.image = [UIImage imageNamed:@"statusupload"];
  3835. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetaskcrypto"] forState:UIControlStateNormal];
  3836. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3837. cell.cancelTaskButton.hidden = NO;
  3838. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3839. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3840. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3841. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusstopcrypto"];
  3842. else cell.statusImageView.image = [UIImage imageNamed:@"statusstop"];
  3843. cell.reloadTaskButton.hidden = NO;
  3844. cell.stopTaskButton.hidden = YES;
  3845. } else {
  3846. if (metadata.cryptated)[cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3847. else [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3848. cell.stopTaskButton.hidden = NO;
  3849. cell.reloadTaskButton.hidden = YES;
  3850. }
  3851. // se non c'è una preview in bianconero metti l'immagine di default
  3852. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3853. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3854. cell.labelTitle.enabled = NO;
  3855. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3856. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3857. if (progress > 0) {
  3858. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3859. else cell.progressView.progressTintColor = [UIColor blackColor];
  3860. cell.progressView.progress = progress;
  3861. cell.progressView.hidden = NO;
  3862. }
  3863. // ----------------------------------------------------------------------------------------------------------
  3864. // uploadFileError
  3865. // ----------------------------------------------------------------------------------------------------------
  3866. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3867. cell.labelTitle.enabled = NO;
  3868. cell.statusImageView.image = [UIImage imageNamed:@"statuserror"];
  3869. if ([metadata.sessionError length] == 0)
  3870. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3871. else
  3872. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3873. }
  3874. }
  3875. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3876. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3877. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3878. return cell;
  3879. }
  3880. - (void)setTableViewFooter
  3881. {
  3882. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3883. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3884. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3885. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3886. UIFont *appFont = [UIFont systemFontOfSize:12];
  3887. footerLabel.font = appFont;
  3888. footerLabel.textColor = [UIColor grayColor];
  3889. footerLabel.backgroundColor = [UIColor clearColor];
  3890. footerLabel.textAlignment = NSTextAlignmentCenter;
  3891. NSString *folders;
  3892. NSString *files;
  3893. NSString *footerText;
  3894. if (_sectionDataSource.directories > 1) {
  3895. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3896. } else if (_sectionDataSource.directories == 1){
  3897. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3898. } else {
  3899. folders = @"";
  3900. }
  3901. if (_sectionDataSource.files > 1) {
  3902. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3903. } else if (_sectionDataSource.files == 1){
  3904. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3905. } else {
  3906. files = @"";
  3907. }
  3908. if ([folders isEqualToString:@""]) {
  3909. footerText = files;
  3910. } else if ([files isEqualToString:@""]) {
  3911. footerText = folders;
  3912. } else {
  3913. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3914. }
  3915. footerLabel.text = footerText;
  3916. [footerView addSubview:footerLabel];
  3917. [self.tableView setTableFooterView:footerView];
  3918. }
  3919. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3920. {
  3921. NSString *textMessage;
  3922. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3923. // se non può essere selezionata deseleziona
  3924. if ([cell isEditing] == NO)
  3925. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3926. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3927. if (self.tableView.editing) {
  3928. [self setTitle];
  3929. return;
  3930. }
  3931. // test crash
  3932. NSArray *metadatas = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  3933. if (indexPath.row >= [metadatas count]) return;
  3934. // settiamo il record file.
  3935. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3936. //
  3937. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  3938. // se è in corso una sessione
  3939. if ([_metadata.session length] > 0) return;
  3940. if (_metadata.errorPasscode) {
  3941. // se UUID è nil lo sta ancora caricando quindi esci
  3942. if (!_metadata.uuid) return;
  3943. // esiste un hint ??
  3944. NSString *hint = [[CCCrypto sharedManager] getHintFromFile:_metadata.fileName isLocal:NO directoryUser:app.directoryUser];
  3945. // qui !! la richiesta della nuova passcode
  3946. if ([_metadata.uuid isEqualToString:[CCUtility getUUID]]) {
  3947. // stesso UUID ... la password è stata modificata !!!!!!
  3948. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_same_device_different_passcode_hint_",nil), hint];
  3949. else textMessage = NSLocalizedString(@"_same_device_different_passcode_", nil);
  3950. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3951. [alertView show];
  3952. } else {
  3953. // UUID diverso.
  3954. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_hint_",nil), _metadata.nameCurrentDevice, hint];
  3955. else textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_",nil), _metadata.nameCurrentDevice];
  3956. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3957. [alertView show];
  3958. }
  3959. // chiediamo la passcode e ricarichiamo tutto.
  3960. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3961. viewController.delegate = self;
  3962. viewController.fromType = CCBKPasscodeFromPasscode;
  3963. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3964. viewController.passcodeInputView.maximumLength = 64;
  3965. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3966. viewController.inputViewTitlePassword = NO;
  3967. viewController.title = [NCBrandOptions sharedInstance].brand;
  3968. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3969. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3970. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3971. [self presentViewController:navigationController animated:YES completion:nil];
  3972. }
  3973. // modello o plist con il title a 0 allora è andato storto qualcosa ... ricaricalo
  3974. if (_metadata.cryptated && [_metadata.title length] == 0) {
  3975. NSString* selector;
  3976. if ([_metadata.type isEqualToString: k_metadataType_template]) selector = selectorLoadModelView;
  3977. else selector = selectorLoadPlist;
  3978. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3979. return;
  3980. }
  3981. // se il plist è caricato ed è un modello aprilo
  3982. if ([_metadata.type isEqualToString:k_metadataType_template]) [self openModel:_metadata.model isNew:false];
  3983. // file
  3984. if (_metadata.directory == NO && _metadata.errorPasscode == NO && [_metadata.type isEqualToString: k_metadataType_file]) {
  3985. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3986. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3987. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3988. } else {
  3989. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3990. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3991. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3992. }
  3993. }
  3994. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3995. }
  3996. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3997. {
  3998. [self setTitle];
  3999. }
  4000. #pragma --------------------------------------------------------------------------------------------
  4001. #pragma mark ===== Synchronize Folder Cell =====
  4002. #pragma --------------------------------------------------------------------------------------------
  4003. - (void)synchronizeFolderGraphicsServerUrl:(NSString *)serverUrl animation:(BOOL)animation
  4004. {
  4005. BOOL cryptated = NO;
  4006. CCCellMain *cell;
  4007. for (NSString* fileID in _sectionDataSource.allRecordsDataSource) {
  4008. tableMetadata *recordMetadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4009. if (recordMetadata.directory == NO)
  4010. continue;
  4011. if ([[CCUtility stringAppendServerUrl:_serverUrl addFileName:recordMetadata.fileNameData] isEqualToString:serverUrl]) {
  4012. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:recordMetadata.fileID];
  4013. cell = (CCCellMain *)[self.tableView cellForRowAtIndexPath:indexPath];
  4014. cryptated = recordMetadata.cryptated;
  4015. break;
  4016. }
  4017. }
  4018. if (!cell)
  4019. return;
  4020. if (animation) {
  4021. NSURL *myURL;
  4022. if (cryptated)
  4023. myURL = [[NSBundle mainBundle] URLForResource: @"synchronizedcrypto" withExtension:@"gif"];
  4024. else
  4025. myURL = [[NSBundle mainBundle] URLForResource: @"synchronized" withExtension:@"gif"];
  4026. } else {
  4027. cell.synchronizedImageView.image = nil;
  4028. }
  4029. }
  4030. #pragma --------------------------------------------------------------------------------------------
  4031. #pragma mark ===== Navigation ====
  4032. #pragma --------------------------------------------------------------------------------------------
  4033. - (BOOL)shouldPerformSegue
  4034. {
  4035. // if background return
  4036. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  4037. if (self.view.window == NO)
  4038. return NO;
  4039. // Collapsed ma siamo già in detail esci
  4040. if (self.splitViewController.isCollapsed)
  4041. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  4042. // Video in esecuzione esci
  4043. if (_detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && _detailViewController.photoBrowser.currentVideoPlayerViewController.view.window) return NO;
  4044. return YES;
  4045. }
  4046. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  4047. {
  4048. id viewController = segue.destinationViewController;
  4049. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  4050. tableMetadata *metadata;
  4051. if ([viewController isKindOfClass:[UINavigationController class]]) {
  4052. UINavigationController *nav = viewController;
  4053. _detailViewController = (CCDetail *)nav.topViewController;
  4054. } else {
  4055. _detailViewController = segue.destinationViewController;
  4056. }
  4057. if ([sender isKindOfClass:[tableMetadata class]]) {
  4058. metadata = sender;
  4059. [allRecordsDataSourceImagesVideos addObject:sender];
  4060. } else {
  4061. metadata = _metadata;
  4062. for (NSString *fileID in _sectionDataSource.allFileID) {
  4063. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4064. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  4065. [allRecordsDataSourceImagesVideos addObject:metadata];
  4066. }
  4067. }
  4068. _detailViewController.metadataDetail = metadata;
  4069. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  4070. _detailViewController.dateFilterQuery = nil;
  4071. _detailViewController.isCameraUpload = NO;
  4072. [_detailViewController setTitle:metadata.fileNamePrint];
  4073. }
  4074. // can i go to next viewcontroller
  4075. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  4076. {
  4077. NSString *nomeDir;
  4078. if(self.tableView.editing == NO && _metadata.errorPasscode == NO){
  4079. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  4080. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  4081. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  4082. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  4083. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4084. viewController.delegate = self;
  4085. viewController.fromType = CCBKPasscodeFromLockDirectory;
  4086. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4087. viewController.inputViewTitlePassword = YES;
  4088. if ([CCUtility getSimplyBlockCode]) {
  4089. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  4090. viewController.passcodeInputView.maximumLength = 6;
  4091. } else {
  4092. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4093. viewController.passcodeInputView.maximumLength = 64;
  4094. }
  4095. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  4096. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  4097. viewController.touchIDManager = touchIDManager;
  4098. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  4099. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4100. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  4101. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4102. [self presentViewController:navController animated:YES completion:nil];
  4103. return;
  4104. }
  4105. if (_metadata.cryptated) nomeDir = [_metadata.fileName substringToIndex:[_metadata.fileName length]-6];
  4106. else nomeDir = _metadata.fileName;
  4107. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  4108. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  4109. if (viewController.isViewLoaded == false || viewController == nil) {
  4110. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  4111. viewController.isFolderEncrypted = _metadata.cryptated;
  4112. viewController.serverUrl = serverUrlPush;
  4113. viewController.titleMain = _metadata.fileNamePrint;
  4114. viewController.textBackButton = _titleMain;
  4115. // save self
  4116. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  4117. }
  4118. // OFF SearchBar
  4119. [viewController cancelSearchBar];
  4120. [self.navigationController pushViewController:viewController animated:YES];
  4121. }
  4122. }
  4123. @end