CCMain.m 254 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729
  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 *metadatas = [[NCManageDatabase sharedInstance] getMetadatasWithPreficate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND session = ''", app.activeAccount, directoryID] sorted:nil ascending:NO];
  1167. for (tableMetadata *metadata in metadatas) {
  1168. if ([CCUtility isCryptoPlistString:metadata.fileName] && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName]] == NO && [metadata.session length] == 0) {
  1169. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1170. metadataNet.action = actionDownloadFile;
  1171. metadataNet.downloadData = NO;
  1172. metadataNet.downloadPlist = YES;
  1173. metadataNet.fileID = metadata.fileID;
  1174. metadataNet.selector = selectorLoadPlist;
  1175. metadataNet.serverUrl = serverUrl;
  1176. metadataNet.session = k_download_session_foreground;
  1177. metadataNet.taskStatus = k_taskStatusResume;
  1178. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1179. }
  1180. }
  1181. }
  1182. #pragma --------------------------------------------------------------------------------------------
  1183. #pragma mark ===== Upload new Photos/Videos =====
  1184. #pragma --------------------------------------------------------------------------------------------
  1185. - (void)uploadFileFailure:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector message:(NSString *)message errorCode:(NSInteger)errorCode
  1186. {
  1187. // Automatic upload All
  1188. if([selector isEqualToString:selectorUploadAutomaticAll])
  1189. [app performSelectorOnMainThread:@selector(loadAutomaticUpload) withObject:nil waitUntilDone:NO];
  1190. // Read File test do not exists
  1191. if (errorCode == k_CCErrorFileUploadNotFound && fileID) {
  1192. //tableMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount] context:nil];
  1193. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", fileID, app.activeAccount]];
  1194. // reUpload
  1195. if (metadata)
  1196. [[CCNetworking sharedNetworking] uploadFileMetadata:metadata taskStatus:k_taskStatusResume];
  1197. }
  1198. // Print error
  1199. else if (errorCode != kCFURLErrorCancelled && errorCode != 403) {
  1200. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1201. }
  1202. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1203. }
  1204. - (void)uploadFileSuccess:(CCMetadataNet *)metadataNet fileID:(NSString *)fileID serverUrl:(NSString *)serverUrl selector:(NSString *)selector selectorPost:(NSString *)selectorPost
  1205. {
  1206. // Automatic upload All
  1207. if([selector isEqualToString:selectorUploadAutomaticAll])
  1208. [app performSelectorOnMainThread:@selector(loadAutomaticUpload) withObject:nil waitUntilDone:NO];
  1209. if ([selectorPost isEqualToString:selectorReadFolderForced] ) {
  1210. [self readFolderWithForced:YES serverUrl:serverUrl];
  1211. } else {
  1212. [self reloadDatasource:serverUrl fileID:nil selector:selector];
  1213. }
  1214. }
  1215. //
  1216. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  1217. //
  1218. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl cryptated:(BOOL)cryptated useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  1219. {
  1220. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
  1221. [self performSelectorOnMainThread:@selector(uploadFileAssetBridge:) withObject:@[assets, serverUrl, [NSNumber numberWithBool:cryptated], [NSNumber numberWithBool:useSubFolder], session] waitUntilDone:NO];
  1222. });
  1223. }
  1224. - (void)uploadFileAssetBridge:(NSArray *)arguments
  1225. {
  1226. NSArray *assets = [arguments objectAtIndex:0];
  1227. NSString *serverUrl = [arguments objectAtIndex:1];
  1228. BOOL cryptated = [[arguments objectAtIndex:2] boolValue];
  1229. BOOL useSubFolder = [[arguments objectAtIndex:3] boolValue];
  1230. NSString *session = [arguments objectAtIndex:4];
  1231. NSString *folderPhotos = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPathAndName:app.activeUrl];
  1232. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount];
  1233. // Create the folder for Photos & if request the subfolders
  1234. if (![app createFolderSubFolderAutomaticUploadFolderPhotos:folderPhotos useSubFolder:useSubFolder assets:assets selector:selectorUploadFile])
  1235. return;
  1236. NSLog(@"[LOG] Asset N. %lu", (unsigned long)[assets count]);
  1237. for (PHAsset *asset in assets) {
  1238. NSString *fileName = [CCUtility createFileNameFromAsset:asset key: k_keyFileNameMask];
  1239. NSDate *assetDate = asset.creationDate;
  1240. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1241. // Create serverUrl if use sub folder
  1242. if (useSubFolder) {
  1243. [formatter setDateFormat:@"yyyy"];
  1244. NSString *yearString = [formatter stringFromDate:assetDate];
  1245. [formatter setDateFormat:@"MM"];
  1246. NSString *monthString = [formatter stringFromDate:assetDate];
  1247. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", folderPhotos, yearString, monthString];
  1248. }
  1249. // Check if is in upload
  1250. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(account = %@) AND (directoryID = %@) AND (fileName = %@) AND (session != '')", app.activeAccount, directoryID, fileName];
  1251. //NSArray *isRecordInSessions = [CCCoreData getTableMetadataWithPredicate:predicate context:nil];
  1252. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPreficate:predicate sorted:nil ascending:NO];
  1253. if ([isRecordInSessions count] > 0) {
  1254. // next upload
  1255. continue;
  1256. } else {
  1257. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1258. metadataNet.action = actionReadFile;
  1259. metadataNet.assetLocalIdentifier = asset.localIdentifier;
  1260. metadataNet.cryptated = cryptated;
  1261. metadataNet.fileName = fileName;
  1262. metadataNet.priority = NSOperationQueuePriorityNormal;
  1263. metadataNet.session = session;
  1264. metadataNet.selector = selectorReadFileUploadFile;
  1265. metadataNet.serverUrl = serverUrl;
  1266. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1267. }
  1268. }
  1269. }
  1270. #pragma --------------------------------------------------------------------------------------------
  1271. #pragma mark ==== Read File ====
  1272. #pragma --------------------------------------------------------------------------------------------
  1273. - (void)readFileFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1274. {
  1275. // UploadFile
  1276. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1277. // File not exists
  1278. if (errorCode == 404) {
  1279. metadataNet.action = actionUploadAsset;
  1280. metadataNet.errorCode = 0;
  1281. metadataNet.selector = selectorUploadFile;
  1282. metadataNet.selectorPost = nil;
  1283. metadataNet.taskStatus = k_taskStatusResume;
  1284. if ([metadataNet.session containsString:@"wwan"])
  1285. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1286. else
  1287. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1288. } else {
  1289. // error ho many retry befor notification and go to on next asses
  1290. if (metadataNet.errorRetry < 3) {
  1291. // Retry read file
  1292. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1293. } else {
  1294. // STOP check file, view message error
  1295. [app messageNotification:@"_upload_file_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1296. }
  1297. }
  1298. }
  1299. }
  1300. - (void)readFileSuccess:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata
  1301. {
  1302. // UploadFile
  1303. if ([metadataNet.selector isEqualToString:selectorReadFileUploadFile]) {
  1304. metadataNet.action = actionUploadAsset;
  1305. metadataNet.errorCode = 403; // File exists 403 Forbidden
  1306. metadataNet.selector = selectorUploadFile;
  1307. metadataNet.selectorPost = nil;
  1308. metadataNet.taskStatus = k_taskStatusResume;
  1309. if ([metadataNet.session containsString:@"wwan"])
  1310. [app addNetworkingOperationQueue:app.netQueueUploadWWan delegate:self metadataNet:metadataNet];
  1311. else
  1312. [app addNetworkingOperationQueue:app.netQueueUpload delegate:self metadataNet:metadataNet];
  1313. }
  1314. }
  1315. #pragma --------------------------------------------------------------------------------------------
  1316. #pragma mark ==== Read Folder ====
  1317. #pragma --------------------------------------------------------------------------------------------
  1318. - (void)readFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1319. {
  1320. // verify active user
  1321. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1322. [_hud hideHud];
  1323. [_refreshControl endRefreshing];
  1324. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1325. if (message && [record.account isEqualToString:metadataNet.account])
  1326. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1327. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1328. if (errorCode == 401)
  1329. [self changePasswordAccount];
  1330. }
  1331. - (void)readFolderSuccess:(CCMetadataNet *)metadataNet permissions:(NSString *)permissions etag:(NSString *)etag metadatas:(NSArray *)metadatas
  1332. {
  1333. // verify active user
  1334. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1335. if (![record.account isEqualToString:metadataNet.account])
  1336. return;
  1337. // save father e update permission
  1338. if(!_isSearchMode)
  1339. _fatherPermission = permissions;
  1340. NSArray *recordsInSessions;
  1341. if (_isSearchMode) {
  1342. //recordsInSessions = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (session != NULL) AND (session != '')", metadataNet.account] context:nil];
  1343. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPreficate:[NSPredicate predicateWithFormat:@"(account = %@) AND (session != '')", metadataNet.account] sorted:nil ascending:NO];
  1344. } else {
  1345. [CCCoreData updateDirectoryEtagServerUrl:metadataNet.serverUrl etag:etag activeAccount:metadataNet.account];
  1346. //[CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND ((session == NULL) OR (session == ''))", metadataNet.account, metadataNet.directoryID]];
  1347. [[NCManageDatabase sharedInstance] deleteMetadata:[NSPredicate predicateWithFormat:@"(account = %@) AND (directoryID = %@) AND (session = '')", metadataNet.account, metadataNet.directoryID]];
  1348. recordsInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPreficate:[NSPredicate predicateWithFormat:@"(account = %@) AND (directoryID = %@) AND (session != '')", metadataNet.account, metadataNet.directoryID] sorted:nil ascending:NO];
  1349. //recordsInSessions = [CCCoreData getTableMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (session != NULL) AND (session != '')", metadataNet.account, metadataNet.directoryID] context:nil];
  1350. [CCCoreData setDateReadDirectoryID:metadataNet.directoryID activeAccount:app.activeAccount];
  1351. }
  1352. for (tableMetadata *metadata in metadatas) {
  1353. // Delete Record only in Search Mode
  1354. if (_isSearchMode) {
  1355. //[CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileID = %@) AND ((session == NULL) OR (session == ''))", metadataNet.account, metadata.directoryID, metadata.fileID]];
  1356. [[NCManageDatabase sharedInstance] deleteMetadata:[NSPredicate predicateWithFormat:@"(account = %@) AND (directoryID = %@) AND (fileID = %@) AND (session = '')", metadataNet.account, metadata.directoryID, metadata.fileID]];
  1357. }
  1358. // type of file
  1359. NSInteger typeFilename = [CCUtility getTypeFileName:metadata.fileName];
  1360. // if crypto do not insert
  1361. if (typeFilename == k_metadataTypeFilenameCrypto) continue;
  1362. // verify if the record encrypted has plist + crypto
  1363. if (typeFilename == k_metadataTypeFilenamePlist && metadata.directory == NO) {
  1364. BOOL isCryptoComplete = NO;
  1365. NSString *fileNameCrypto = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  1366. for (tableMetadata *completeMetadata in metadatas) {
  1367. if (completeMetadata.cryptated == NO) continue;
  1368. else if ([completeMetadata.fileName isEqualToString:fileNameCrypto]) {
  1369. isCryptoComplete = YES;
  1370. break;
  1371. }
  1372. }
  1373. if (isCryptoComplete == NO) continue;
  1374. }
  1375. // verify if the record is in download/upload progress
  1376. if (metadata.directory == NO && [recordsInSessions count] > 0) {
  1377. //tableMetadata *metadataDB = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileName == %@)", app.activeAccount, metadataNet.directoryID, metadata.fileName] context:nil];
  1378. tableMetadata *metadataDB = [[NCManageDatabase sharedInstance] getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@) AND (fileName == %@)", app.activeAccount, metadataNet.directoryID, metadata.fileName]];
  1379. // is in Upload
  1380. if (metadataDB.session && [metadataDB.session containsString:@"upload"]) {
  1381. NSString *sessionID = metadataDB.sessionID;
  1382. // rename SessionID -> fileID
  1383. [CCUtility moveFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, sessionID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]];
  1384. metadataDB.session = @"";
  1385. metadataDB.date = metadata.date;
  1386. metadataDB.fileID = metadata.fileID;
  1387. metadataDB.rev = metadata.fileID;
  1388. metadataDB.sessionError = @"";
  1389. metadataDB.sessionID = @"";
  1390. metadataDB.sessionTaskIdentifier = k_taskIdentifierDone;
  1391. metadataDB.sessionTaskIdentifierPlist = k_taskIdentifierDone;
  1392. //[CCCoreData updateMetadata:metadataDB predicate:[NSPredicate predicateWithFormat:@"(sessionID == %@) AND (account == %@)", sessionID, app.activeAccount] activeAccount:app.activeAccount activeUrl:app.activeUrl context:nil];
  1393. //[[NCManageDatabase sharedInstance] updateMetadata:metadataDB activeUrl:app.activeUrl];
  1394. [CCCoreData addLocalFile:metadataDB activeAccount:app.activeAccount];
  1395. [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]];
  1396. continue;
  1397. }
  1398. // download in progress
  1399. if (metadataDB.session && [metadataDB.session containsString:@"download"])
  1400. continue;
  1401. }
  1402. // end test, insert in CoreData
  1403. [[NCManageDatabase sharedInstance] addMetadata:metadata activeUrl:app.activeUrl];
  1404. }
  1405. // read plist
  1406. [self downloadPlist:metadataNet.directoryID serverUrl:metadataNet.serverUrl];
  1407. // File is changed ??
  1408. if (!_isSearchMode)
  1409. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatas serverUrl:metadataNet.serverUrl account:app.activeAccount withDownload:NO];
  1410. // Search Mode
  1411. if (_isSearchMode)
  1412. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1413. // this is the same directory
  1414. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1415. // reload
  1416. [self reloadDatasource:metadataNet.serverUrl fileID:nil selector:metadataNet.selector];
  1417. // stoprefresh
  1418. [_refreshControl endRefreshing];
  1419. // Enable change user
  1420. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1421. [_hud hideHud];
  1422. }
  1423. }
  1424. - (void)readFolderWithForced:(BOOL)forced serverUrl:(NSString *)serverUrl
  1425. {
  1426. // init control
  1427. if (!serverUrl || !app.activeAccount)
  1428. return;
  1429. // Search Mode
  1430. if (_isSearchMode) {
  1431. if (forced) {
  1432. [CCCoreData clearDateReadAccount:app.activeAccount serverUrl:serverUrl directoryID:nil];
  1433. _searchFileName = @""; // forced reload searchg
  1434. }
  1435. [self updateSearchResultsForSearchController:self.searchController];
  1436. return;
  1437. }
  1438. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount];
  1439. if ([CCCoreData isDirectoryOutOfDate:k_dayForceReadFolder directoryID:directoryID activeAccount:app.activeAccount] || forced) {
  1440. if (_refreshControl.isRefreshing == NO)
  1441. [_hud visibleIndeterminateHud];
  1442. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1443. metadataNet.action = actionReadFolder;
  1444. metadataNet.date = [NSDate date];
  1445. metadataNet.directoryID = directoryID;
  1446. metadataNet.priority = NSOperationQueuePriorityHigh;
  1447. metadataNet.selector = selectorReadFolder;
  1448. metadataNet.serverUrl = serverUrl;
  1449. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1450. }
  1451. }
  1452. #pragma mark -
  1453. #pragma --------------------------------------------------------------------------------------------
  1454. #pragma mark ===== Search =====
  1455. #pragma --------------------------------------------------------------------------------------------
  1456. -(void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1457. {
  1458. _isSearchMode = YES;
  1459. [self deleteRefreshControl];
  1460. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1461. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1462. _searchFileName = fileName;
  1463. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12 && ![_depth isEqualToString:@"0"]) {
  1464. [[CCActions sharedInstance] search:_serverUrl fileName:_searchFileName depth:_depth delegate:self];
  1465. _noFilesSearchTitle = @"";
  1466. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1467. [self.tableView reloadEmptyDataSet];
  1468. } else {
  1469. NSString *directoryID = [CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount];
  1470. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(directoryID == %@) AND (account == %@) AND (fileNamePrint CONTAINS[cd] %@)", directoryID, app.activeAccount, fileName];
  1471. //NSArray *records = [CCCoreData getTableMetadataWithPredicate:predicate context:nil];
  1472. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPreficate:predicate sorted:nil ascending:NO];
  1473. [_searchResultMetadatas removeAllObjects];
  1474. for (tableMetadata *record in records)
  1475. [_searchResultMetadatas addObject:record];
  1476. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1477. metadataNet.account = app.activeAccount;
  1478. metadataNet.action = actionUploadTemplate;
  1479. metadataNet.directoryID = directoryID;
  1480. metadataNet.selector = selectorSearch;
  1481. metadataNet.serverUrl = _serverUrl;
  1482. [self readFolderSuccess:metadataNet permissions:@"" etag:@"" metadatas:_searchResultMetadatas];
  1483. }
  1484. }
  1485. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1486. [self reloadDatasource];
  1487. }
  1488. }
  1489. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1490. {
  1491. [self cancelSearchBar];
  1492. [self readFolderWithForced:NO serverUrl:_serverUrl];
  1493. }
  1494. - (void)searchFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1495. {
  1496. _searchFileName = @"";
  1497. if (message)
  1498. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1499. }
  1500. - (void)searchSuccess:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas
  1501. {
  1502. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1503. [self readFolderSuccess:metadataNet permissions:nil etag:nil metadatas:metadatas];
  1504. }
  1505. - (void)cancelSearchBar
  1506. {
  1507. if (self.searchController.active) {
  1508. [self.searchController setActive:NO];
  1509. [self createRefreshControl];
  1510. _isSearchMode = NO;
  1511. _searchFileName = @"";
  1512. _dateReadDataSource = nil;
  1513. _searchResultMetadatas = [NSMutableArray new];
  1514. [self reloadDatasource];
  1515. }
  1516. }
  1517. - (void)searchBar:(UISearchBar *)searchBar selectedScopeButtonIndexDidChange:(NSInteger)selectedScope
  1518. {
  1519. NSString *title = [self.searchController.searchBar.scopeButtonTitles objectAtIndex:selectedScope];
  1520. self.searchController.searchBar.placeholder = title;
  1521. if ([title isEqualToString:NSLocalizedString(@"_search_this_folder_",nil)])
  1522. _depth = @"0";
  1523. if ([title isEqualToString:NSLocalizedString(@"_search_sub_folder_",nil)])
  1524. _depth = @"1";
  1525. if ([title isEqualToString:NSLocalizedString(@"_search_all_folders_",nil)])
  1526. _depth = @"infinity";
  1527. _searchFileName = @"";
  1528. [self updateSearchResultsForSearchController:self.searchController];
  1529. }
  1530. #pragma mark -
  1531. #pragma --------------------------------------------------------------------------------------------
  1532. #pragma mark ===== Delete File or Folder =====
  1533. #pragma --------------------------------------------------------------------------------------------
  1534. - (void)deleteFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1535. {
  1536. [self deleteFileOrFolderSuccess:metadataNet];
  1537. }
  1538. - (void)deleteFileOrFolderSuccess:(CCMetadataNet *)metadataNet
  1539. {
  1540. [_queueSelector removeObject:metadataNet.selector];
  1541. if ([_queueSelector count] == 0) {
  1542. [_hud hideHud];
  1543. if (_isSearchMode)
  1544. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1545. else
  1546. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1547. // next
  1548. if ([_selectedMetadatas count] > 0) {
  1549. [_selectedMetadatas removeObjectAtIndex:0];
  1550. if ([_selectedMetadatas count] > 0)
  1551. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1552. }
  1553. }
  1554. }
  1555. - (void)deleteFileOrFolder:(tableMetadata *)metadata numFile:(NSInteger)numFile ofFile:(NSInteger)ofFile
  1556. {
  1557. if (metadata.cryptated) {
  1558. [_queueSelector addObject:selectorDeleteCrypto];
  1559. [_queueSelector addObject:selectorDeletePlist];
  1560. } else {
  1561. [_queueSelector addObject:selectorDelete];
  1562. }
  1563. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1564. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1565. }
  1566. - (void)deleteSelectionFile
  1567. {
  1568. [_selectedMetadatas removeAllObjects];
  1569. [_queueSelector removeAllObjects];
  1570. _selectedMetadatas = [[NSMutableArray alloc] initWithArray: [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]]];
  1571. _numSelectedMetadatas = [_selectedMetadatas count];
  1572. if ([_selectedMetadatas count] > 0)
  1573. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1574. [self tableViewSelect:NO];
  1575. }
  1576. - (void)deleteFile
  1577. {
  1578. [_selectedMetadatas removeAllObjects];
  1579. [_queueSelector removeAllObjects];
  1580. _numSelectedMetadatas = 1;
  1581. [_selectedMetadatas addObject:_metadata];
  1582. if ([_selectedMetadatas count] > 0)
  1583. [self deleteFileOrFolder:[_selectedMetadatas objectAtIndex:0] numFile:[_selectedMetadatas count] ofFile:_numSelectedMetadatas];
  1584. [self tableViewSelect:NO];
  1585. }
  1586. #pragma --------------------------------------------------------------------------------------------
  1587. #pragma mark ===== Rename / Move =====
  1588. #pragma --------------------------------------------------------------------------------------------
  1589. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1590. {
  1591. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1592. }
  1593. - (void)renameFile:(tableMetadata *)metadata fileName:(NSString *)fileName
  1594. {
  1595. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1596. }
  1597. - (void)renameNote:(tableMetadata *)metadata fileName:(NSString *)fileName
  1598. {
  1599. CCTemplates *templates = [[CCTemplates alloc] init];
  1600. NSMutableDictionary *field = [[CCCrypto sharedManager] getDictionaryEncrypted:metadata.fileName uuid:metadata.uuid isLocal:NO directoryUser:app.directoryUser];
  1601. NSString *fileNameModel = [templates salvaNote:[field objectForKey:@"note"] titolo:fileName fileName:metadata.fileName uuid:metadata.uuid];
  1602. if (fileNameModel) {
  1603. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1604. metadataNet.action = actionUploadTemplate;
  1605. metadataNet.fileName = [CCUtility trasformedFileNamePlistInCrypto:fileNameModel];
  1606. metadataNet.fileNamePrint = fileName;
  1607. metadataNet.rev = metadata.rev;
  1608. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1609. metadataNet.session = k_upload_session_foreground;
  1610. metadataNet.taskStatus = k_taskStatusResume;
  1611. if ([CCCoreData isOfflineLocalFileID:metadata.fileID activeAccount:app.activeAccount])
  1612. metadataNet.selectorPost = selectorAddOffline;
  1613. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1614. }
  1615. }
  1616. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1617. {
  1618. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1619. [_hud hideHud];
  1620. if (message)
  1621. [app messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1622. [_selectedMetadatas removeAllObjects];
  1623. [_queueSelector removeAllObjects];
  1624. }
  1625. }
  1626. - (void)moveSuccess:(CCMetadataNet *)metadataNet revTo:(NSString *)revTo
  1627. {
  1628. [_queueSelector removeObject:metadataNet.selector];
  1629. if ([_queueSelector count] == 0) {
  1630. [_hud hideHud];
  1631. NSString *fileName = [CCUtility trasformedFileNameCryptoInPlist:metadataNet.fileName];
  1632. NSString *directoryID = metadataNet.directoryID;
  1633. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1634. NSString *serverUrlTo = [CCCoreData getServerUrlFromDirectoryID:directoryIDTo activeAccount:app.activeAccount];
  1635. // FILE -> Metadata
  1636. if (metadataNet.directory == NO) {
  1637. // move metadata
  1638. //[CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1639. [[NCManageDatabase sharedInstance] moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1640. }
  1641. // DIRECTORY -> Directory - CCMetadata
  1642. if (metadataNet.directory == YES) {
  1643. // delete all dir / subdir
  1644. NSArray *directoryIDs = [CCCoreData deleteDirectoryAndSubDirectory:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName] activeAccount:app.activeAccount];
  1645. // delete all metadata and local file in dir / subdir
  1646. for (NSString *directoryIDDelete in directoryIDs) {
  1647. //[CCCoreData deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"(directoryID == %@)AND (account == %@)",directoryIDDelete, app.activeAccount]];
  1648. [[NCManageDatabase sharedInstance] deleteMetadata:[NSPredicate predicateWithFormat:@"(directoryID == %@)AND (account == %@)",directoryIDDelete, app.activeAccount]];
  1649. }
  1650. // move metadata
  1651. //[CCCoreData moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo activeAccount:app.activeAccount];
  1652. [[NCManageDatabase sharedInstance] moveMetadata:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1653. // Add new directory
  1654. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1655. [CCCoreData addDirectory:newDirectory permissions:nil activeAccount:app.activeAccount];
  1656. // Check Offline
  1657. if ([CCCoreData isOfflineDirectoryServerUrl:serverUrlTo activeAccount:app.activeAccount])
  1658. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1659. }
  1660. // reload Datasource
  1661. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1662. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1663. else
  1664. [self reloadDatasource];
  1665. // Next file
  1666. [_selectedMetadatas removeObjectAtIndex:0];
  1667. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:metadataNet.serverUrlTo waitUntilDone:NO];
  1668. }
  1669. }
  1670. - (void)moveFileOrFolder:(NSString *)serverUrlTo
  1671. {
  1672. if ([_selectedMetadatas count] > 0) {
  1673. tableMetadata *metadata = [_selectedMetadatas objectAtIndex:0];
  1674. // Plain
  1675. if (metadata.cryptated == NO) {
  1676. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:app.activeUser withPassword:app.activePassword withUrl:app.activeUrl isCryptoCloudMode:NO];
  1677. NSError *error = [ocNetworking readFileSync:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName]];
  1678. if(!error) {
  1679. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1680. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1681. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1682. }];
  1683. [alert addAction:ok];
  1684. [self presentViewController:alert animated:YES completion:nil];
  1685. });
  1686. return;
  1687. }
  1688. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1689. metadataNet.action = actionMoveFileOrFolder;
  1690. metadataNet.directory = metadata.directory;
  1691. metadataNet.fileID = metadata.fileID;
  1692. metadataNet.directoryID = metadata.directoryID;
  1693. metadataNet.directoryIDTo = [CCCoreData getDirectoryIDFromServerUrl:serverUrlTo activeAccount:app.activeAccount];
  1694. metadataNet.fileName = metadata.fileName;
  1695. metadataNet.fileNamePrint = metadataNet.fileNamePrint;
  1696. metadataNet.fileNameTo = metadata.fileName;
  1697. metadataNet.rev = metadata.rev;
  1698. metadataNet.selector = selectorMove;
  1699. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1700. metadataNet.serverUrlTo = serverUrlTo;
  1701. [_queueSelector addObject:metadataNet.selector];
  1702. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1703. }
  1704. // cyptated
  1705. if (metadata.cryptated == YES) {
  1706. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1707. metadataNet.action = actionMoveFileOrFolder;
  1708. metadataNet.directory = metadata.directory;
  1709. metadataNet.fileID = metadata.fileID;
  1710. metadataNet.directoryID = metadata.directoryID;
  1711. metadataNet.directoryIDTo = [CCCoreData getDirectoryIDFromServerUrl:serverUrlTo activeAccount:app.activeAccount];
  1712. metadataNet.fileNamePrint = metadata.fileNamePrint;
  1713. metadataNet.rev = metadata.rev;
  1714. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1715. metadataNet.serverUrlTo = serverUrlTo;
  1716. // data
  1717. metadataNet.fileName = metadata.fileNameData;
  1718. metadataNet.fileNameTo = metadata.fileNameData;
  1719. metadataNet.selector = selectorMoveCrypto;
  1720. [_queueSelector addObject:metadataNet.selector];
  1721. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1722. // plist
  1723. metadataNet.fileName = metadata.fileName;
  1724. metadataNet.fileNameTo = metadata.fileName;
  1725. metadataNet.selector = selectorMovePlist;
  1726. [_queueSelector addObject:metadataNet.selector];
  1727. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1728. }
  1729. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), _numSelectedMetadatas - [_selectedMetadatas count] + 1, _numSelectedMetadatas] mode:MBProgressHUDModeIndeterminate color:nil];
  1730. }
  1731. }
  1732. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title selectedMetadatas:(NSArray *)selectedMetadatas
  1733. {
  1734. [_selectedMetadatas removeAllObjects];
  1735. [_queueSelector removeAllObjects];
  1736. _selectedMetadatas = [[NSMutableArray alloc] initWithArray:selectedMetadatas];
  1737. _numSelectedMetadatas = [_selectedMetadatas count];
  1738. [self performSelectorOnMainThread:@selector(moveFileOrFolder:) withObject:serverUrlTo waitUntilDone:NO];
  1739. [self tableViewSelect:NO];
  1740. }
  1741. - (void)moveOpenWindow:(NSArray *)indexPaths
  1742. {
  1743. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1744. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1745. viewController.delegate = self;
  1746. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1747. viewController.selectedMetadatas = [self getMetadatasFromSelectedRows:indexPaths];
  1748. viewController.tintColor = [NCBrandColor sharedInstance].navigationBarText;
  1749. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1750. viewController.tintColorTitle = [NCBrandColor sharedInstance].navigationBarText;
  1751. viewController.networkingOperationQueue = app.netQueue;
  1752. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1753. [self presentViewController:navigationController animated:YES completion:nil];
  1754. }
  1755. #pragma --------------------------------------------------------------------------------------------
  1756. #pragma mark ===== Create folder =====
  1757. #pragma --------------------------------------------------------------------------------------------
  1758. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1759. {
  1760. [_hud hideHud];
  1761. if (message)
  1762. [app messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1763. }
  1764. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1765. {
  1766. [_hud hideHud];
  1767. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1768. [CCCoreData addDirectory:newDirectory permissions:nil activeAccount:app.activeAccount];
  1769. // Check Offline
  1770. if ([CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount])
  1771. [CCCoreData setOfflineDirectoryServerUrl:newDirectory offline:YES activeAccount:app.activeAccount];
  1772. // Load Folder or the Datasource
  1773. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced]) {
  1774. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  1775. } else {
  1776. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  1777. }
  1778. }
  1779. - (void)createFolder:(NSString *)fileNameFolder folderCameraUpload:(BOOL)folderCameraUpload
  1780. {
  1781. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1782. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1783. if (![fileNameFolder length]) return;
  1784. if (folderCameraUpload) metadataNet.serverUrl = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPath:app.activeUrl];
  1785. else metadataNet.serverUrl = _serverUrl;
  1786. metadataNet.action = actionCreateFolder;
  1787. if (folderCameraUpload)
  1788. metadataNet.options = @"folderCameraUpload";
  1789. metadataNet.fileName = fileNameFolder;
  1790. metadataNet.selector = selectorCreateFolder;
  1791. metadataNet.selectorPost = selectorReadFolderForced;
  1792. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1793. if (!folderCameraUpload)
  1794. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1795. }
  1796. - (void)createFolderEncrypted:(NSString *)fileNameFolder
  1797. {
  1798. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1799. NSString *fileNamePlist;
  1800. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1801. if (![fileNameFolder length]) return;
  1802. NSString *title = [AESCrypt encrypt:fileNameFolder password:[[CCCrypto sharedManager] getKeyPasscode:[CCUtility getUUID]]];
  1803. fileNamePlist = [[CCCrypto sharedManager] createFilenameEncryptor:fileNameFolder uuid:[CCUtility getUUID]];
  1804. [[CCCrypto sharedManager] createFilePlist:[NSTemporaryDirectory() stringByAppendingString:fileNamePlist] title:title len:0 directory:true uuid:[CCUtility getUUID] nameCurrentDevice:[CCUtility getNameCurrentDevice] icon:@""];
  1805. // Create folder
  1806. metadataNet.action = actionCreateFolder;
  1807. metadataNet.fileName = fileNamePlist;
  1808. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1809. metadataNet.selector = selectorCreateFolder;
  1810. metadataNet.serverUrl = _serverUrl;
  1811. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1812. // upload plist file
  1813. metadataNet.action = actionUploadOnlyPlist;
  1814. metadataNet.fileName = [fileNamePlist stringByAppendingString:@".plist"];
  1815. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1816. metadataNet.selectorPost = selectorReadFolderForced;
  1817. metadataNet.serverUrl = _serverUrl;
  1818. metadataNet.session = k_upload_session_foreground;
  1819. metadataNet.taskStatus = k_taskStatusResume;
  1820. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1821. [_hud visibleHudTitle:NSLocalizedString(@"_create_folder_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1822. }
  1823. - (void)createFolderCameraUpload
  1824. {
  1825. NSString *cameraFolderName = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderName];
  1826. [self createFolder:cameraFolderName folderCameraUpload:YES];
  1827. }
  1828. #pragma --------------------------------------------------------------------------------------------
  1829. #pragma mark ===== Encrypted / Decrypted Folder =====
  1830. #pragma --------------------------------------------------------------------------------------------
  1831. - (void)encyptedDecryptedFolder
  1832. {
  1833. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  1834. if (_metadata.cryptated) {
  1835. // DECRYPTED
  1836. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1837. //-------------------------- RENAME -------------------------------------------//
  1838. metadataNet.action = actionMoveFileOrFolder;
  1839. metadataNet.fileID = _metadata.fileID;
  1840. metadataNet.fileName = _metadata.fileNameData;
  1841. metadataNet.fileNameTo = _metadata.fileNamePrint;
  1842. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1843. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1844. metadataNet.selector = selectorRename;
  1845. metadataNet.serverUrl = serverUrl;
  1846. metadataNet.serverUrlTo = serverUrl;
  1847. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1848. //-------------------------- DELETE -------------------------------------------//
  1849. metadataNet.action = actionDeleteFileDirectory;
  1850. metadataNet.fileID = _metadata.fileID;
  1851. metadataNet.fileName = _metadata.fileName;
  1852. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1853. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1854. metadataNet.selector = selectorDeletePlist;
  1855. metadataNet.selectorPost = selectorReadFolderForced;
  1856. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1857. } else {
  1858. // ENCRYPTED
  1859. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  1860. // Create File Plist
  1861. NSString *fileNameCrypto = [[CCCrypto sharedManager] createFileDirectoryPlist:_metadata];
  1862. //-------------------------- RENAME -------------------------------------------//
  1863. metadataNet.action = actionMoveFileOrFolder;
  1864. metadataNet.fileID = _metadata.fileID;
  1865. metadataNet.fileName = _metadata.fileName;
  1866. metadataNet.fileNamePrint = _metadata.fileNamePrint;
  1867. metadataNet.fileNameTo = fileNameCrypto;
  1868. metadataNet.priority = NSOperationQueuePriorityVeryHigh;
  1869. metadataNet.selector = selectorRename;
  1870. metadataNet.serverUrl = serverUrl;
  1871. metadataNet.serverUrlTo = serverUrl;
  1872. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1873. //-------------------------- UPLOAD -------------------------------------------//
  1874. metadataNet.action = actionUploadOnlyPlist;
  1875. metadataNet.fileName = [fileNameCrypto stringByAppendingString:@".plist"];
  1876. metadataNet.priority = NSOperationQueuePriorityVeryLow;
  1877. metadataNet.selectorPost = selectorReadFolderForced;
  1878. metadataNet.serverUrl = serverUrl;
  1879. metadataNet.session = k_upload_session_foreground;
  1880. metadataNet.taskStatus = k_taskStatusResume;
  1881. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  1882. }
  1883. }
  1884. #pragma --------------------------------------------------------------------------------------------
  1885. #pragma mark ===== Encrypted/Decrypted File =====
  1886. #pragma --------------------------------------------------------------------------------------------
  1887. - (void)encryptedSelectedFiles
  1888. {
  1889. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1890. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1891. for (tableMetadata *metadata in selectedMetadatas) {
  1892. if (metadata.cryptated == NO && metadata.directory == NO)
  1893. [metadatas addObject:metadata];
  1894. }
  1895. if ([metadatas count] > 0) {
  1896. NSLog(@"[LOG] Start encrypted selected files ...");
  1897. for (tableMetadata* metadata in metadatas) {
  1898. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1899. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorEncryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1900. }
  1901. }
  1902. [self tableViewSelect:NO];
  1903. }
  1904. - (void)decryptedSelectedFiles
  1905. {
  1906. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  1907. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  1908. for (tableMetadata *metadata in selectedMetadatas) {
  1909. if (metadata.cryptated == YES && metadata.directory == NO && [metadata.model length] == 0)
  1910. [metadatas addObject:metadata];
  1911. }
  1912. if ([metadatas count] > 0) {
  1913. NSLog(@"[LOG] Start decrypted selected files ...");
  1914. for (tableMetadata* metadata in metadatas) {
  1915. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  1916. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorDecryptFile selectorPost:nil session:k_download_session taskStatus: k_taskStatusResume delegate:self];
  1917. }
  1918. }
  1919. [self tableViewSelect:NO];
  1920. }
  1921. - (void)cmdEncryptedDecryptedFile
  1922. {
  1923. NSString *selector;
  1924. if (_metadata.cryptated == YES) selector = selectorDecryptFile;
  1925. if (_metadata.cryptated == NO) selector = selectorEncryptFile;
  1926. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  1927. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  1928. }
  1929. - (void)encryptedFile:(tableMetadata *)metadata
  1930. {
  1931. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1932. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1933. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1934. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1935. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:app.activeAccount];
  1936. dispatch_async(dispatch_get_main_queue(), ^{
  1937. [[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];
  1938. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1939. });
  1940. } else {
  1941. [app messageNotification:@"_encrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1942. }
  1943. }
  1944. - (void)decryptedFile:(tableMetadata *)metadata
  1945. {
  1946. NSString *fileNameFrom = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID];
  1947. NSString *fileNameTo = [NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint];
  1948. [[NSFileManager defaultManager] copyItemAtPath:fileNameFrom toPath:fileNameTo error:nil];
  1949. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNameTo]) {
  1950. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:app.activeAccount];
  1951. dispatch_async(dispatch_get_main_queue(), ^{
  1952. [[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];
  1953. [self performSelector:@selector(reloadDatasource) withObject:nil];
  1954. });
  1955. } else {
  1956. [app messageNotification:@"_decrypted_selected_files_" description:@"_file_not_present_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1957. }
  1958. }
  1959. #pragma --------------------------------------------------------------------------------------------
  1960. #pragma mark ===== Progress & Task Button =====
  1961. #pragma --------------------------------------------------------------------------------------------
  1962. - (void)triggerProgressTask:(NSNotification *)notification
  1963. {
  1964. NSDictionary *dict = notification.userInfo;
  1965. NSString *fileID = [dict valueForKey:@"fileID"];
  1966. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1967. BOOL cryptated = [[dict valueForKey:@"cryptated"] boolValue];
  1968. float progress = [[dict valueForKey:@"progress"] floatValue];
  1969. // Check
  1970. if (!fileID)
  1971. return;
  1972. [app.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1973. if (![serverUrl isEqualToString:_serverUrl])
  1974. return;
  1975. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1976. if (indexPath) {
  1977. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1978. if (cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  1979. else cell.progressView.progressTintColor = [UIColor blackColor];
  1980. cell.progressView.hidden = NO;
  1981. [cell.progressView setProgress:progress];
  1982. }
  1983. if (progress == 0)
  1984. [self.navigationController cancelCCProgress];
  1985. else
  1986. [self.navigationController setCCProgressPercentage:progress*100 andTintColor: [NCBrandColor sharedInstance].navigationBarProgress];
  1987. }
  1988. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1989. {
  1990. UITouch * touch = [[event allTouches] anyObject];
  1991. CGPoint location = [touch locationInView:self.tableView];
  1992. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  1993. if (indexPath) {
  1994. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  1995. if (metadata)
  1996. [self reloadTaskButton:metadata];
  1997. }
  1998. }
  1999. - (void)reloadTaskButton:(tableMetadata *)metadata
  2000. {
  2001. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2002. __block NSURLSessionTask *findTask;
  2003. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2004. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2005. NSString *fileID = metadata.fileID;
  2006. // DOWNLOAD
  2007. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2008. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2009. for (NSURLSessionUploadTask *task in downloadTasks)
  2010. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2011. findTask = task;
  2012. [app.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  2013. [task cancel];
  2014. }
  2015. if (!findTask) {
  2016. dispatch_async(dispatch_get_main_queue(), ^{
  2017. [app.listChangeTask setObject:@"reloadDownload" forKey:metadata.fileID];
  2018. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2019. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2020. });
  2021. }
  2022. }];
  2023. }
  2024. // UPLOAD
  2025. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2026. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2027. for (NSURLSessionUploadTask *task in uploadTasks)
  2028. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2029. findTask = task;
  2030. [app.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  2031. [task cancel];
  2032. }
  2033. if (!findTask) {
  2034. dispatch_async(dispatch_get_main_queue(), ^{
  2035. [app.listChangeTask setObject:@"reloadUpload" forKey:metadata.fileID];
  2036. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2037. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2038. });
  2039. }
  2040. }];
  2041. }
  2042. }
  2043. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  2044. {
  2045. UITouch * touch = [[event allTouches] anyObject];
  2046. CGPoint location = [touch locationInView:self.tableView];
  2047. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2048. if (indexPath) {
  2049. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2050. if (metadata)
  2051. [self cancelTaskButton:metadata reloadTable:YES];
  2052. }
  2053. }
  2054. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  2055. {
  2056. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2057. __block NSURLSessionTask *findTask;
  2058. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2059. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2060. NSString *fileID = metadata.fileID;
  2061. // DOWNLOAD
  2062. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  2063. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2064. for (NSURLSessionTask *task in downloadTasks)
  2065. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2066. findTask = task;
  2067. [app.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  2068. [task cancel];
  2069. }
  2070. if (!findTask) {
  2071. dispatch_async(dispatch_get_main_queue(), ^{
  2072. [app.listChangeTask setObject:@"cancelDownload" forKey:metadata.fileID];
  2073. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2074. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2075. });
  2076. }
  2077. }];
  2078. }
  2079. // UPLOAD
  2080. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2081. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2082. for (NSURLSessionUploadTask *task in uploadTasks)
  2083. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2084. findTask = task;
  2085. [app.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  2086. [task cancel];
  2087. }
  2088. if (!findTask) {
  2089. dispatch_async(dispatch_get_main_queue(), ^{
  2090. [app.listChangeTask setObject:@"cancelUpload" forKey:metadata.fileID];
  2091. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2092. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2093. });
  2094. }
  2095. }];
  2096. }
  2097. }
  2098. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  2099. {
  2100. UITouch * touch = [[event allTouches] anyObject];
  2101. CGPoint location = [touch locationInView:self.tableView];
  2102. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2103. if (indexPath) {
  2104. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2105. if (metadata)
  2106. [self stopTaskButton:metadata];
  2107. }
  2108. }
  2109. - (void)stopTaskButton:(tableMetadata *)metadata
  2110. {
  2111. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  2112. __block NSURLSessionTask *findTask;
  2113. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  2114. NSInteger sessionTaskIdentifierPlist = metadata.sessionTaskIdentifierPlist;
  2115. NSString *fileID = metadata.fileID;
  2116. // UPLOAD
  2117. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  2118. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  2119. for (NSURLSessionUploadTask *task in uploadTasks)
  2120. if (task.taskIdentifier == sessionTaskIdentifier || task.taskIdentifier == sessionTaskIdentifierPlist) {
  2121. [app.listChangeTask setObject:@"stopUpload" forKey:fileID];
  2122. findTask = task;
  2123. [task cancel];
  2124. }
  2125. if (!findTask) {
  2126. dispatch_async(dispatch_get_main_queue(), ^{
  2127. [app.listChangeTask setObject:@"stopUpload" forKey:metadata.fileID];
  2128. NSArray *object = [[NSArray alloc] initWithObjects:session, metadata, findTask, nil];
  2129. [[NSNotificationCenter defaultCenter] postNotificationName:k_networkingSessionNotification object:object];
  2130. });
  2131. }
  2132. }];
  2133. }
  2134. }
  2135. #pragma --------------------------------------------------------------------------------------------
  2136. #pragma mark ===== Shared =====
  2137. #pragma --------------------------------------------------------------------------------------------
  2138. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  2139. {
  2140. [_hud hideHud];
  2141. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2142. // change account ?
  2143. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  2144. if([record.account isEqualToString:metadataNet.account] == NO)
  2145. return;
  2146. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  2147. if (result) {
  2148. appDelegate.sharesLink = result[0];
  2149. appDelegate.sharesUserAndGroup = result[1];
  2150. }
  2151. if (openWindow) {
  2152. if (_shareOC) {
  2153. [_shareOC reloadData];
  2154. } else {
  2155. //tableMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount] context:nil];
  2156. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount]];
  2157. // Apriamo la view
  2158. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  2159. _shareOC.delegate = self;
  2160. _shareOC.metadata = metadata;
  2161. _shareOC.serverUrl = metadataNet.serverUrl;
  2162. _shareOC.shareLink = [app.sharesLink objectForKey:metadata.fileID];
  2163. _shareOC.shareUserAndGroup = [app.sharesUserAndGroup objectForKey:metadata.fileID];
  2164. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  2165. [self presentViewController:_shareOC animated:YES completion:nil];
  2166. }
  2167. }
  2168. [self tableViewReload];
  2169. }
  2170. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2171. {
  2172. [_hud hideHud];
  2173. [app messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2174. if (_shareOC)
  2175. [_shareOC reloadData];
  2176. [self tableViewReload];
  2177. if (errorCode == 401)
  2178. [self changePasswordAccount];
  2179. }
  2180. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  2181. {
  2182. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2183. metadataNet.action = actionShare;
  2184. metadataNet.fileID = metadata.fileID;
  2185. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2186. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2187. metadataNet.password = password;
  2188. metadataNet.selector = selectorShare;
  2189. metadataNet.serverUrl = serverUrl;
  2190. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2191. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2192. }
  2193. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  2194. {
  2195. [_hud hideHud];
  2196. AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  2197. // rimuoviamo la condivisione da db
  2198. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  2199. if (result) {
  2200. appDelegate.sharesLink = result[0];
  2201. appDelegate.sharesUserAndGroup = result[1];
  2202. }
  2203. if (_shareOC)
  2204. [_shareOC reloadData];
  2205. [self tableViewReload];
  2206. }
  2207. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  2208. {
  2209. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2210. metadataNet.action = actionUnShare;
  2211. metadataNet.fileID = metadata.fileID;
  2212. metadataNet.fileName = metadata.fileName;
  2213. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2214. metadataNet.selector = selectorUnshare;
  2215. metadataNet.serverUrl = serverUrl;
  2216. metadataNet.share = share;
  2217. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2218. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2219. }
  2220. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2221. {
  2222. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2223. metadataNet.action = actionUpdateShare;
  2224. metadataNet.fileID = metadata.fileID;
  2225. metadataNet.expirationTime = expirationTime;
  2226. metadataNet.password = password;
  2227. metadataNet.selector = selectorUpdateShare;
  2228. metadataNet.serverUrl = serverUrl;
  2229. metadataNet.share = share;
  2230. metadataNet.sharePermission = permission;
  2231. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2232. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2233. }
  2234. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2235. {
  2236. [_hud hideHud];
  2237. if (_shareOC)
  2238. [_shareOC reloadUserAndGroup:items];
  2239. }
  2240. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2241. {
  2242. [_hud hideHud];
  2243. [app messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2244. }
  2245. - (void)getUserAndGroup:(NSString *)find
  2246. {
  2247. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2248. metadataNet.action = actionGetUserAndGroup;
  2249. metadataNet.options = find;
  2250. metadataNet.selector = selectorGetUserAndGroup;
  2251. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2252. [_hud visibleIndeterminateHud];
  2253. }
  2254. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2255. {
  2256. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2257. metadataNet.action = actionShareWith;
  2258. metadataNet.fileID = metadata.fileID;
  2259. metadataNet.directoryID = directoryID;
  2260. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:app.activeUrl];
  2261. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2262. metadataNet.serverUrl = serverUrl;
  2263. metadataNet.selector = selectorShare;
  2264. metadataNet.share = user;
  2265. metadataNet.shareeType = shareeType;
  2266. metadataNet.sharePermission = permission;
  2267. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2268. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2269. }
  2270. - (void)openWindowShare:(tableMetadata *)metadata
  2271. {
  2272. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:app.activeAccount];
  2273. metadataNet.action = actionReadShareServer;
  2274. metadataNet.fileID = metadata.fileID;
  2275. metadataNet.fileName = metadata.fileName;
  2276. metadataNet.fileNamePrint = metadata.fileNamePrint;
  2277. metadataNet.selector = selectorOpenWindowShare;
  2278. metadataNet.serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2279. [app addNetworkingOperationQueue:app.netQueue delegate:self metadataNet:metadataNet];
  2280. [_hud visibleIndeterminateHud];
  2281. }
  2282. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2283. {
  2284. CGPoint location = [tapGesture locationInView:self.tableView];
  2285. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2286. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2287. if (metadata)
  2288. [self openWindowShare:metadata];
  2289. }
  2290. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2291. {
  2292. CGPoint location = [tapGesture locationInView:self.tableView];
  2293. NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:location];
  2294. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2295. if (metadata) {
  2296. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2297. vc.metadata = metadata;
  2298. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2299. [self presentViewController:vc animated:YES completion:nil];
  2300. }
  2301. }
  2302. #pragma --------------------------------------------------------------------------------------------
  2303. #pragma mark ===== Favorite =====
  2304. #pragma --------------------------------------------------------------------------------------------
  2305. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2306. {
  2307. //[CCCoreData setMetadataFavoriteFileID:metadataNet.fileID favorite:[metadataNet.options boolValue] activeAccount:app.activeAccount context:nil];
  2308. _dateReadDataSource = nil;
  2309. [[NCManageDatabase sharedInstance] setMetadataFavorite:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2310. if (_isSearchMode)
  2311. [self readFolderWithForced:YES serverUrl:metadataNet.serverUrl];
  2312. else
  2313. [self reloadDatasource:metadataNet.serverUrl fileID:metadataNet.fileID selector:metadataNet.selector];
  2314. //tableMetadata *metadata = [CCCoreData getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount] context:nil];
  2315. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPreficate:[NSPredicate predicateWithFormat:@"(fileID == %@) AND (account == %@)", metadataNet.fileID, app.activeAccount]];
  2316. if (metadata.directory && metadata.favorite) {
  2317. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileNameData];
  2318. [[CCSynchronize sharedSynchronize] addFavoriteFolder:dir];
  2319. }
  2320. }
  2321. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2322. {
  2323. }
  2324. - (void)addFavorite:(tableMetadata *)metadata
  2325. {
  2326. if (metadata.directory) {
  2327. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2328. } else {
  2329. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2330. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2331. }
  2332. }
  2333. - (void)removeFavorite:(tableMetadata *)metadata
  2334. {
  2335. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2336. }
  2337. #pragma --------------------------------------------------------------------------------------------
  2338. #pragma mark ===== Offline =====
  2339. #pragma --------------------------------------------------------------------------------------------
  2340. - (void)addOffline:(tableMetadata *)metadata
  2341. {
  2342. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2343. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddOffline selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2344. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2345. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2346. }
  2347. - (void)removeOffline:(tableMetadata *)metadata
  2348. {
  2349. [CCCoreData setOfflineLocalFileID:metadata.fileID offline:NO activeAccount:app.activeAccount];
  2350. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2351. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2352. }
  2353. #pragma --------------------------------------------------------------------------------------------
  2354. #pragma mark ===== Local =====
  2355. #pragma --------------------------------------------------------------------------------------------
  2356. - (void)addLocal:(tableMetadata *)metadata
  2357. {
  2358. if (metadata.errorPasscode || !metadata.uuid) return;
  2359. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2360. if ([metadata.type isEqualToString: k_metadataType_file])
  2361. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorAddLocal selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2362. if ([metadata.type isEqualToString: k_metadataType_template]) {
  2363. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileName] toPath:[NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryLocal], metadata.fileName]];
  2364. [app messageNotification:@"_add_local_" description:@"_file_saved_local_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  2365. }
  2366. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2367. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2368. }
  2369. #pragma --------------------------------------------------------------------------------------------
  2370. #pragma mark ===== Open in... =====
  2371. #pragma --------------------------------------------------------------------------------------------
  2372. - (void)openIn:(tableMetadata *)metadata
  2373. {
  2374. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  2375. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2376. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2377. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2378. }
  2379. #pragma --------------------------------------------------------------------------------------------
  2380. #pragma mark ===== Remove Local File =====
  2381. #pragma --------------------------------------------------------------------------------------------
  2382. - (void)removeLocalFile:(tableMetadata *)metadata
  2383. {
  2384. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2385. [CCCoreData deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"(account == %@) AND (fileID == %@)", app.activeAccount, metadata.fileID]];
  2386. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID] error:nil];
  2387. [self reloadDatasource:serverUrl fileID:metadata.fileID selector:nil];
  2388. }
  2389. #pragma --------------------------------------------------------------------------------------------
  2390. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2391. #pragma --------------------------------------------------------------------------------------------
  2392. - (void)orderTable:(NSString *)order
  2393. {
  2394. [CCUtility setOrderSettings:order];
  2395. // Clear data-read of DataSource
  2396. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2397. }
  2398. - (void)ascendingTable:(BOOL)ascending
  2399. {
  2400. [CCUtility setAscendingSettings:ascending];
  2401. // Clear data-read of DataSource
  2402. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2403. }
  2404. - (void)directoryOnTop:(BOOL)directoryOnTop
  2405. {
  2406. [CCUtility setDirectoryOnTop:directoryOnTop];
  2407. // Clear data-read of DataSource
  2408. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2409. }
  2410. - (void)tableGroupBy:(NSString *)groupBy
  2411. {
  2412. [CCUtility setGroupBySettings:groupBy];
  2413. // Clear data-read of DataSource
  2414. [[NSNotificationCenter defaultCenter] postNotificationName:@"clearDateReadDataSource" object:nil];
  2415. }
  2416. #pragma --------------------------------------------------------------------------------------------
  2417. #pragma mark ==== Menu LOGO ====
  2418. #pragma --------------------------------------------------------------------------------------------
  2419. - (void)menuLogo
  2420. {
  2421. if (app.reSelectMenu.isOpen || app.reMainMenu.isOpen)
  2422. return;
  2423. // Brand
  2424. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2425. return;
  2426. 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) {
  2427. [app messageNotification:@"_transfers_in_queue_" description:nil visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  2428. return;
  2429. }
  2430. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2431. NSMutableArray *menuArray = [NSMutableArray new];
  2432. for (NSString *account in listAccount) {
  2433. if ([account isEqualToString:app.activeAccount]) continue;
  2434. CCMenuItem *item = [[CCMenuItem alloc] init];
  2435. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2436. item.argument = account;
  2437. item.image = [UIImage imageNamed:@"menuLogoUser"];
  2438. item.target = self;
  2439. item.action = @selector(changeDefaultAccount:);
  2440. [menuArray addObject:item];
  2441. }
  2442. if ([menuArray count] == 0)
  2443. return;
  2444. OptionalConfiguration options;
  2445. Color textColor, backgroundColor;
  2446. textColor.R = 0;
  2447. textColor.G = 0;
  2448. textColor.B = 0;
  2449. backgroundColor.R = 1;
  2450. backgroundColor.G = 1;
  2451. backgroundColor.B = 1;
  2452. NSInteger originY = 60;
  2453. options.arrowSize = 9;
  2454. options.marginXSpacing = 7;
  2455. options.marginYSpacing = 10;
  2456. options.intervalSpacing = 20;
  2457. options.menuCornerRadius = 6.5;
  2458. options.maskToBackground = NO;
  2459. options.shadowOfMenu = YES;
  2460. options.hasSeperatorLine = YES;
  2461. options.seperatorLineHasInsets = YES;
  2462. options.textColor = textColor;
  2463. options.menuBackgroundColor = backgroundColor;
  2464. CGRect rect = self.view.frame;
  2465. rect.origin.y = rect.origin.y + originY;
  2466. rect.size.height = rect.size.height - originY;
  2467. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2468. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2469. }
  2470. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2471. {
  2472. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2473. // STOP, erase all in queue networking
  2474. [app cancelAllOperations];
  2475. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:k_taskStatusCancel activeAccount:app.activeAccount activeUser:app.activeUser activeUrl:app.activeUrl];
  2476. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2477. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2478. if (tableAccount)
  2479. [app settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activePassword:tableAccount.password];
  2480. // go to home sweet home
  2481. [[NSNotificationCenter defaultCenter] postNotificationName:@"initializeMain" object:nil];
  2482. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2483. });
  2484. }
  2485. #pragma --------------------------------------------------------------------------------------------
  2486. #pragma mark ==== ReMenu ====
  2487. #pragma --------------------------------------------------------------------------------------------
  2488. - (void)createReMenuBackgroundView:(REMenu *)menu
  2489. {
  2490. __block CGFloat navigationBarH = self.navigationController.navigationBar.frame.size.height + [UIApplication sharedApplication].statusBarFrame.size.height;
  2491. _reMenuBackgroundView.frame = CGRectMake(0, navigationBarH, self.view.frame.size.width, self.view.frame.size.height);
  2492. [UIView animateWithDuration:0.2 animations:^{
  2493. float height = (self.view.frame.size.height + navigationBarH) - (menu.menuView.frame.size.height - self.navigationController.navigationBar.frame.size.height + 3);
  2494. if (height < self.tabBarController.tabBar.frame.size.height)
  2495. height = self.tabBarController.tabBar.frame.size.height;
  2496. _reMenuBackgroundView.frame = CGRectMake(0, self.view.frame.size.height + navigationBarH, self.view.frame.size.width, - height);
  2497. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2498. }];
  2499. }
  2500. - (void)createReMainMenu
  2501. {
  2502. NSString *ordinamento;
  2503. NSString *groupBy = _directoryGroupBy;
  2504. __block NSString *nuovoOrdinamento;
  2505. NSString *titoloNuovo, *titoloAttuale;
  2506. BOOL ascendente;
  2507. __block BOOL nuovoAscendente;
  2508. UIImage *image;
  2509. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2510. app.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2511. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2512. [self tableViewSelect:YES];
  2513. }
  2514. }];
  2515. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2516. ordinamento = _directoryOrder;
  2517. if ([ordinamento isEqualToString:@"fileName"]) {
  2518. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brand];
  2519. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2520. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2521. nuovoOrdinamento = @"fileDate";
  2522. }
  2523. if ([ordinamento isEqualToString:@"fileDate"]) {
  2524. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brand];
  2525. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2526. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2527. nuovoOrdinamento = @"fileName";
  2528. }
  2529. app.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2530. [self orderTable:nuovoOrdinamento];
  2531. }];
  2532. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2533. ascendente = [CCUtility getAscendingSettings];
  2534. if (ascendente) {
  2535. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brand];
  2536. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2537. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2538. nuovoAscendente = false;
  2539. }
  2540. if (!ascendente) {
  2541. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brand];
  2542. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2543. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2544. nuovoAscendente = true;
  2545. }
  2546. app.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2547. [self ascendingTable:nuovoAscendente];
  2548. }];
  2549. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2550. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2551. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2552. app.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2553. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2554. else [self tableGroupBy:@"alphabetic"];
  2555. }];
  2556. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2557. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2558. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2559. app.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2560. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2561. else [self tableGroupBy:@"typefile"];
  2562. }];
  2563. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2564. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2565. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2566. app.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2567. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2568. else [self tableGroupBy:@"date"];
  2569. }];
  2570. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2571. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2572. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2573. app.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brand] highlightedImage:nil action:^(REMenuItem *item) {
  2574. if ([CCUtility getDirectoryOnTop]) [self directoryOnTop:NO];
  2575. else [self directoryOnTop:YES];
  2576. }];
  2577. // REMENU --------------------------------------------------------------------------------------------------------------
  2578. app.reMainMenu = [[REMenu alloc] initWithItems:@[app.selezionaItem, app.ordinaItem, app.ascendenteItem, app.alphabeticItem, app.typefileItem, app.dateItem, app.directoryOnTopItem]];
  2579. app.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2580. app.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2581. app.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2582. app.reMainMenu.waitUntilAnimationIsComplete = NO;
  2583. app.reMainMenu.separatorHeight = 0.5;
  2584. app.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2585. app.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2586. app.reMainMenu.textColor = [UIColor blackColor];
  2587. app.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2588. app.reMainMenu.textShadowColor = nil;
  2589. app.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2590. app.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2591. app.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2592. app.reMainMenu.highlightedSeparatorColor = nil;
  2593. app.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2594. app.reMainMenu.highlightedTextShadowColor = nil;
  2595. app.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2596. app.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2597. app.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2598. app.reMainMenu.subtitleTextShadowColor = nil;
  2599. app.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2600. app.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2601. app.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2602. app.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2603. app.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2604. app.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2605. app.reMainMenu.borderWidth = 0.3;
  2606. app.reMainMenu.borderColor = [UIColor lightGrayColor];
  2607. app.reMainMenu.animationDuration = 0.2;
  2608. app.reMainMenu.closeAnimationDuration = 0.2;
  2609. app.reMainMenu.bounce = NO;
  2610. [app.reMainMenu setClosePreparationBlock:^{
  2611. // Backgroun reMenu (Gesture)
  2612. [_reMenuBackgroundView removeFromSuperview];
  2613. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2614. }];
  2615. }
  2616. - (void)toggleReMainMenu
  2617. {
  2618. if (app.reMainMenu.isOpen) {
  2619. [app.reMainMenu close];
  2620. } else {
  2621. [self createReMainMenu];
  2622. [app.reMainMenu showFromNavigationController:self.navigationController];
  2623. // Backgroun reMenu & (Gesture)
  2624. [self createReMenuBackgroundView:app.reMainMenu];
  2625. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2626. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2627. }
  2628. }
  2629. - (void)createReSelectMenu
  2630. {
  2631. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2632. 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) {
  2633. [self deleteSelectionFile];
  2634. }];
  2635. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2636. 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) {
  2637. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2638. }];
  2639. if (app.isCryptoCloudMode) {
  2640. // ITEM ENCRYPTED ------------------------------------------------------------------------------------------------------
  2641. 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) {
  2642. [self performSelector:@selector(encryptedSelectedFiles) withObject:nil];
  2643. }];
  2644. // ITEM DECRYPTED ----------------------------------------------------------------------------------------------------
  2645. 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) {
  2646. [self performSelector:@selector(decryptedSelectedFiles) withObject:nil];
  2647. }];
  2648. }
  2649. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2650. 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) {
  2651. [self downloadSelectedFiles];
  2652. }];
  2653. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2654. 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) {
  2655. [self saveSelectedFiles];
  2656. }];
  2657. // REMENU --------------------------------------------------------------------------------------------------------------
  2658. if (app.isCryptoCloudMode) {
  2659. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.encryptItem, app.decryptItem, app.downloadItem, app.saveItem]];
  2660. } else {
  2661. app.reSelectMenu = [[REMenu alloc] initWithItems:@[app.deleteItem,app.moveItem, app.downloadItem, app.saveItem]];
  2662. }
  2663. app.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2664. app.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2665. app.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2666. app.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2667. app.reSelectMenu.separatorHeight = 0.5;
  2668. app.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2669. app.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].menuBackground;
  2670. app.reSelectMenu.textColor = [UIColor blackColor];
  2671. app.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2672. app.reSelectMenu.textShadowColor = nil;
  2673. app.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2674. app.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2675. app.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2676. app.reSelectMenu.highlightedSeparatorColor = nil;
  2677. app.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2678. app.reSelectMenu.highlightedTextShadowColor = nil;
  2679. app.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2680. app.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2681. app.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2682. app.reSelectMenu.subtitleTextShadowColor = nil;
  2683. app.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2684. app.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2685. app.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2686. app.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2687. app.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2688. app.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2689. app.reSelectMenu.borderWidth = 0.3;
  2690. app.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2691. app.reSelectMenu.closeAnimationDuration = 0.2;
  2692. app.reSelectMenu.animationDuration = 0.2;
  2693. app.reSelectMenu.bounce = NO;
  2694. [app.reSelectMenu setClosePreparationBlock:^{
  2695. // Backgroun reMenu (Gesture)
  2696. [_reMenuBackgroundView removeFromSuperview];
  2697. [_reMenuBackgroundView removeGestureRecognizer:_singleFingerTap];
  2698. }];
  2699. }
  2700. - (void)toggleReSelectMenu
  2701. {
  2702. if (app.reSelectMenu.isOpen) {
  2703. [app.reSelectMenu close];
  2704. } else {
  2705. [self createReSelectMenu];
  2706. [app.reSelectMenu showFromNavigationController:self.navigationController];
  2707. // Backgroun reMenu & (Gesture)
  2708. [self createReMenuBackgroundView:app.reSelectMenu];
  2709. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2710. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2711. }
  2712. }
  2713. #pragma --------------------------------------------------------------------------------------------
  2714. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2715. #pragma --------------------------------------------------------------------------------------------
  2716. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2717. {
  2718. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2719. UITableView *tableView = (UITableView*)self.view;
  2720. CGPoint touchPoint = [recognizer locationInView:self.view];
  2721. NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:touchPoint];
  2722. if (indexPath)
  2723. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2724. else
  2725. _metadata = nil;
  2726. [self becomeFirstResponder];
  2727. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2728. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2729. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2730. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2731. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2732. UIMenuItem *pasteFileEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_encrypted_", nil) action:@selector(pasteFileEncrypted:)];
  2733. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2734. UIMenuItem *pasteFilesEncryptedItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_encrypted_", nil) action:@selector(pasteFilesEncrypted:)];
  2735. if (app.isCryptoCloudMode)
  2736. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, pasteFileEncryptedItem, pasteFilesEncryptedItem, nil]];
  2737. else
  2738. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2739. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:tableView];
  2740. [menuController setMenuVisible:YES animated:YES];
  2741. }
  2742. }
  2743. - (BOOL)canBecomeFirstResponder
  2744. {
  2745. return YES;
  2746. }
  2747. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2748. {
  2749. // For copy file, copy files, Open in ... :
  2750. //
  2751. // NO Directory
  2752. // NO Error Passcode
  2753. // NO In Session mode (download/upload)
  2754. // NO Template
  2755. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2756. if (_isSelectedMode == NO && _metadata && !_metadata.directory && !_metadata.errorPasscode && [_metadata.session length] == 0 && ![_metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2757. // NO Cryptated with Title lenght = 0
  2758. if (!_metadata.cryptated || (_metadata.cryptated && _metadata.title.length > 0))
  2759. return YES;
  2760. }
  2761. return NO;
  2762. }
  2763. if (@selector(copyFiles:) == action) {
  2764. if (_isSelectedMode) {
  2765. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2766. for (tableMetadata *metadata in selectedMetadatas) {
  2767. if (!metadata.directory && !metadata.errorPasscode && metadata.session.length == 0 && ![metadata.typeFile isEqualToString: k_metadataTypeFile_template]) {
  2768. // NO Cryptated with Title lenght = 0
  2769. if (!metadata.cryptated || (metadata.cryptated && metadata.title.length > 0))
  2770. return YES;
  2771. }
  2772. }
  2773. }
  2774. return NO;
  2775. }
  2776. if (@selector(pasteFile:) == action || @selector(pasteFileEncrypted:) == action) {
  2777. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2778. NSArray *items = [pasteboard items];
  2779. if ([items count] == 1) {
  2780. // Value : (NSData) metadata
  2781. NSDictionary *dic = [items objectAtIndex:0];
  2782. NSData *dataMetadata = [dic objectForKey: k_metadataKeyedUnarchiver];
  2783. tableMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2784. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2785. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2786. if (directoryUser) {
  2787. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2788. return YES;
  2789. }
  2790. return NO;
  2791. } else return NO;
  2792. }
  2793. if (@selector(pasteFiles:) == action || @selector(pasteFilesEncrypted:) == action) {
  2794. BOOL isValid = NO;
  2795. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2796. NSArray *items = [pasteboard items];
  2797. if ([items count] <= 1) return NO;
  2798. for (NSDictionary *dic in items) {
  2799. // Value : (NSData) metadata
  2800. NSData *dataMetadata = [dic objectForKey: k_metadataKeyedUnarchiver];
  2801. tableMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2802. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2803. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2804. if (directoryUser) {
  2805. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]])
  2806. isValid = YES;
  2807. }
  2808. }
  2809. return isValid;
  2810. }
  2811. return NO;
  2812. }
  2813. /************************************ COPY ************************************/
  2814. - (void)copyFile:(id)sender
  2815. {
  2816. // Remove all item
  2817. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2818. pasteboard.items = [[NSArray alloc] init];
  2819. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser,_metadata.fileID]]) {
  2820. [self copyFileToPasteboard:_metadata];
  2821. } else {
  2822. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2823. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2824. }
  2825. }
  2826. - (void)copyFiles:(id)sender
  2827. {
  2828. // Remove all item
  2829. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2830. pasteboard.items = [[NSArray alloc] init];
  2831. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2832. for (tableMetadata *metadata in selectedMetadatas) {
  2833. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]]) {
  2834. [self copyFileToPasteboard:metadata];
  2835. } else {
  2836. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2837. [[CCNetworking sharedNetworking] downloadFile:metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2838. }
  2839. }
  2840. [self tableViewSelect:NO];
  2841. }
  2842. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2843. {
  2844. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2845. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2846. // Value : (NSData) metadata
  2847. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata], k_metadataKeyedUnarchiver,nil];
  2848. [items addObject:item];
  2849. [pasteboard setItems:items];
  2850. }
  2851. /************************************ OPEN IN ... ************************************/
  2852. - (void)openinFile:(id)sender
  2853. {
  2854. [self openIn:_metadata];
  2855. }
  2856. /************************************ PASTE ************************************/
  2857. - (void)pasteFile:(id)sender
  2858. {
  2859. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2860. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2861. }
  2862. - (void)pasteFileEncrypted:(id)sender
  2863. {
  2864. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2865. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2866. }
  2867. - (void)pasteFiles:(id)sender
  2868. {
  2869. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2870. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2871. }
  2872. - (void)pasteFilesEncrypted:(id)sender
  2873. {
  2874. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2875. [self uploadFilePasteArray:[pasteboard items] cryptated:YES];
  2876. }
  2877. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2878. {
  2879. for (NSDictionary *dic in items) {
  2880. // Value : (NSData) metadata
  2881. NSData *dataMetadata = [dic objectForKey: k_metadataKeyedUnarchiver];
  2882. tableMetadata *metadata = [NSKeyedUnarchiver unarchiveObjectWithData:dataMetadata];
  2883. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountActive];
  2884. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2885. if (directoryUser) {
  2886. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID]]) {
  2887. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileNamePrint]];
  2888. [[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];
  2889. }
  2890. }
  2891. }
  2892. }
  2893. #pragma --------------------------------------------------------------------------------------------
  2894. #pragma mark ===== Lock Passcode =====
  2895. #pragma --------------------------------------------------------------------------------------------
  2896. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2897. {
  2898. return _failedAttempts;
  2899. }
  2900. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2901. {
  2902. return _lockUntilDate;
  2903. }
  2904. - (void)passcodeViewCloseButtonPressed:(id)sender
  2905. {
  2906. [self dismissViewControllerAnimated:YES completion:nil];
  2907. }
  2908. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2909. {
  2910. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2911. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2912. _lockUntilDate = nil;
  2913. _failedAttempts = 0;
  2914. aResultHandler(YES);
  2915. } else aResultHandler(NO);
  2916. } else aResultHandler(YES);
  2917. }
  2918. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2919. {
  2920. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2921. switch (aViewController.type) {
  2922. case BKPasscodeViewControllerCheckPasscodeType: {
  2923. if (aViewController.fromType == CCBKPasscodeFromPasscode) {
  2924. // verifichiamo se il passcode è corretto per il seguente file -> UUID
  2925. if ([[CCCrypto sharedManager] verifyPasscode:aPasscode uuid:_metadata.uuid text:_metadata.title]) {
  2926. // scriviamo il passcode
  2927. [CCUtility setKeyChainPasscodeForUUID:_metadata.uuid conPasscode:aPasscode];
  2928. [self readFolderWithForced:YES serverUrl:_serverUrl];
  2929. } else {
  2930. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_error_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2931. [alertView show];
  2932. }
  2933. }
  2934. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2935. // possiamo procedere alla prossima directory
  2936. [self performSegueDirectoryWithControlPasscode:false];
  2937. // avviamo la sessione Passcode Lock con now
  2938. app.sessionePasscodeLock = [NSDate date];
  2939. }
  2940. // disattivazione lock cartella
  2941. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2942. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2943. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2944. if ([CCCoreData setDirectoryUnLock:lockServerUrl activeAccount:app.activeAccount] == NO) {
  2945. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2946. }
  2947. [self.tableView reloadData];
  2948. }
  2949. }
  2950. break;
  2951. default:
  2952. break;
  2953. }
  2954. }
  2955. - (void)comandoLockPassword
  2956. {
  2957. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  2958. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  2959. // se non è abilitato il Lock Passcode esci
  2960. if ([[CCUtility getBlockCode] length] == 0) {
  2961. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  2962. [alertView show];
  2963. return;
  2964. }
  2965. // se è richiesta la disattivazione si chiede la password
  2966. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2967. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2968. viewController.delegate = self;
  2969. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2970. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2971. viewController.inputViewTitlePassword = YES;
  2972. if ([CCUtility getSimplyBlockCode]) {
  2973. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2974. viewController.passcodeInputView.maximumLength = 6;
  2975. } else {
  2976. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2977. viewController.passcodeInputView.maximumLength = 64;
  2978. }
  2979. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2980. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2981. viewController.touchIDManager = touchIDManager;
  2982. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2983. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2984. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  2985. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2986. [self presentViewController:navigationController animated:YES completion:nil];
  2987. return;
  2988. }
  2989. // ---------------- ACTIVATE PASSWORD
  2990. if([CCCoreData setDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) {
  2991. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2992. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2993. } else {
  2994. [app messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2995. }
  2996. }
  2997. #pragma mark -
  2998. #pragma --------------------------------------------------------------------------------------------
  2999. #pragma mark ===== Swipe Tablet -> menu =====
  3000. #pragma --------------------------------------------------------------------------------------------
  3001. // more
  3002. - (NSString *)tableView:(UITableView *)tableView titleForSwipeAccessoryButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
  3003. return NSLocalizedString(@"_more_", nil);
  3004. }
  3005. - (void)tableView:(UITableView *)tableView swipeAccessoryButtonPushedForRowAtIndexPath:(NSIndexPath *)indexPath
  3006. {
  3007. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3008. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  3009. NSString *titoloCriptaDecripta, *titoloOffline, *titoloLock, *titleOfflineFolder, *titleFavorite;
  3010. BOOL offlineFolder = NO;
  3011. if (_metadata.cryptated) titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_decrypt_", nil)];
  3012. else titoloCriptaDecripta = [NSString stringWithFormat:NSLocalizedString(@"_encrypt_", nil)];
  3013. if ([CCCoreData isOfflineLocalFileID:_metadata.fileID activeAccount:app.activeAccount]) titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  3014. else titoloOffline = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  3015. NSString *offlineServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3016. if (_metadata.directory && [CCCoreData isOfflineDirectoryServerUrl:offlineServerUrl activeAccount:app.activeAccount]) {
  3017. titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_remove_offline_", nil)];
  3018. offlineFolder = YES;
  3019. } else titleOfflineFolder = [NSString stringWithFormat:NSLocalizedString(@"_add_offline_", nil)];
  3020. if (_metadata.favorite) {
  3021. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  3022. } else {
  3023. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  3024. }
  3025. if (_metadata.directory) {
  3026. // calcolo lockServerUrl
  3027. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3028. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount]) titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  3029. else titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  3030. }
  3031. TableLocalFile *recordLocalFile = [CCCoreData getLocalFileWithFileID:_metadata.fileID activeAccount:app.activeAccount];
  3032. /******************************************* AHKActionSheet *******************************************/
  3033. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.view title:nil];
  3034. actionSheet.animationDuration = 0.2;
  3035. actionSheet.blurRadius = 0.0f;
  3036. actionSheet.blurTintColor = [UIColor colorWithWhite:0.0f alpha:0.50f];
  3037. actionSheet.buttonHeight = 50.0;
  3038. actionSheet.cancelButtonHeight = 50.0f;
  3039. actionSheet.separatorHeight = 5.0f;
  3040. actionSheet.automaticallyTintButtonImages = @(NO);
  3041. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].cryptocloud };
  3042. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3043. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].brand };
  3044. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  3045. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  3046. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  3047. /******************************************* DIRECTORY *******************************************/
  3048. if (_metadata.directory) {
  3049. BOOL lockDirectory = NO;
  3050. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  3051. // Directory bloccata ?
  3052. if ([CCCoreData isDirectoryLock:dirServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3053. NSString *cameraUploadFolderName = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderName];
  3054. NSString *cameraUploadFolderPath = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPath:app.activeUrl];
  3055. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3056. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:_metadata.iconName] color:[NCBrandColor sharedInstance].brand]
  3057. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3058. height: 50.0
  3059. type: AHKActionSheetButtonTypeDisabled
  3060. handler: nil
  3061. ];
  3062. if (!lockDirectory && !_metadata.cryptated) {
  3063. [actionSheet addButtonWithTitle:titleFavorite
  3064. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3065. backgroundColor:[UIColor whiteColor]
  3066. height: 50.0
  3067. type:AHKActionSheetButtonTypeDefault
  3068. handler:^(AHKActionSheet *as) {
  3069. // close swipe
  3070. [self setEditing:NO animated:YES];
  3071. if (_metadata.favorite)
  3072. [self removeFavorite:_metadata];
  3073. else
  3074. [self addFavorite:_metadata];
  3075. }];
  3076. }
  3077. if (_metadata.cryptated == NO && !lockDirectory) {
  3078. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3079. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3080. backgroundColor:[UIColor whiteColor]
  3081. height: 50.0
  3082. type:AHKActionSheetButtonTypeDefault
  3083. handler:^(AHKActionSheet *as) {
  3084. // close swipe
  3085. [self setEditing:NO animated:YES];
  3086. [self openWindowShare:_metadata];
  3087. }];
  3088. }
  3089. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3090. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3091. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3092. backgroundColor:[UIColor whiteColor]
  3093. height: 50.0
  3094. type:AHKActionSheetButtonTypeDefault
  3095. handler:^(AHKActionSheet *as) {
  3096. // close swipe
  3097. [self setEditing:NO animated:YES];
  3098. //chiediamo il nome del file
  3099. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3100. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3101. alertView.tag = alertRename;
  3102. UITextField *textField = [alertView textFieldAtIndex:0];
  3103. textField.text = _metadata.fileNamePrint;
  3104. [alertView show];
  3105. }];
  3106. }
  3107. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory) {
  3108. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3109. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3110. backgroundColor:[UIColor whiteColor]
  3111. height: 50.0
  3112. type:AHKActionSheetButtonTypeDefault
  3113. handler:^(AHKActionSheet *as) {
  3114. // close swipe
  3115. [self setEditing:NO animated:YES];
  3116. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3117. }];
  3118. }
  3119. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && _metadata.cryptated == NO) {
  3120. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  3121. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brand]
  3122. backgroundColor:[UIColor whiteColor]
  3123. height: 50.0
  3124. type:AHKActionSheetButtonTypeDefault
  3125. handler:^(AHKActionSheet *as) {
  3126. // close swipe
  3127. [self setEditing:NO animated:YES];
  3128. // Settings new folder Automatatic upload
  3129. NSString *oldPath = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPath:app.activeUrl];
  3130. [[NCManageDatabase sharedInstance] setAccountCameraUploadFolderName:_metadata.fileName];
  3131. [[NCManageDatabase sharedInstance] setAccountCameraUploadFolderPath:serverUrl activeUrl:app.activeUrl];
  3132. [CCCoreData clearDateReadAccount:app.activeAccount serverUrl:oldPath directoryID:nil];
  3133. if (app.activeAccount.length > 0 && app.activePhotosCameraUpload)
  3134. [app.activePhotosCameraUpload reloadDatasourceForced];
  3135. [self readFolderWithForced:YES serverUrl:serverUrl];
  3136. NSLog(@"[LOG] Update Folder Photo");
  3137. NSString *folderCameraUpload = [[NCManageDatabase sharedInstance] getAccountCameraUploadFolderPathAndName:app.activeUrl];
  3138. if ([folderCameraUpload length] > 0)
  3139. [[CCSynchronize sharedSynchronize] readFolderServerUrl:folderCameraUpload directoryID:[CCCoreData getDirectoryIDFromServerUrl:folderCameraUpload activeAccount:app.activeAccount] selector:selectorReadFolder];
  3140. }];
  3141. }
  3142. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES)) {
  3143. [actionSheet addButtonWithTitle:titoloLock
  3144. image:[UIImage imageNamed:@"actionSheetLock"]
  3145. backgroundColor:[UIColor whiteColor]
  3146. height: 50.0
  3147. type:AHKActionSheetButtonTypeEncrypted
  3148. handler:^(AHKActionSheet *as) {
  3149. // close swipe
  3150. [self setEditing:NO animated:YES];
  3151. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3152. }];
  3153. }
  3154. if (!([_metadata.fileName isEqualToString:cameraUploadFolderName] == YES && [serverUrl isEqualToString:cameraUploadFolderPath] == YES) && !lockDirectory && app.isCryptoCloudMode) {
  3155. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3156. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3157. backgroundColor:[UIColor whiteColor]
  3158. height: 50.0
  3159. type:AHKActionSheetButtonTypeEncrypted
  3160. handler:^(AHKActionSheet *as) {
  3161. // close swipe
  3162. [self setEditing:NO animated:YES];
  3163. [self performSelector:@selector(encyptedDecryptedFolder) withObject:nil];
  3164. }];
  3165. }
  3166. [actionSheet show];
  3167. }
  3168. /******************************************* FILE *******************************************/
  3169. if ([_metadata.type isEqualToString: k_metadataType_file] && !_metadata.directory) {
  3170. UIImage *iconHeader;
  3171. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3172. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]])
  3173. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, _metadata.fileID]];
  3174. else
  3175. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3176. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3177. image: iconHeader
  3178. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3179. height: 50.0
  3180. type: AHKActionSheetButtonTypeDisabled
  3181. handler: nil
  3182. ];
  3183. if (!_metadata.cryptated) {
  3184. [actionSheet addButtonWithTitle:titleFavorite
  3185. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetFavorite"] color:[NCBrandColor sharedInstance].brand]
  3186. backgroundColor:[UIColor whiteColor]
  3187. height: 50.0
  3188. type:AHKActionSheetButtonTypeDefault
  3189. handler:^(AHKActionSheet *as) {
  3190. // close swipe
  3191. [self setEditing:NO animated:YES];
  3192. if (_metadata.favorite)
  3193. [self removeFavorite:_metadata];
  3194. else
  3195. [self addFavorite:_metadata];
  3196. }];
  3197. }
  3198. if (_metadata.cryptated == NO) {
  3199. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3200. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand]
  3201. backgroundColor:[UIColor whiteColor]
  3202. height: 50.0
  3203. type:AHKActionSheetButtonTypeDefault
  3204. handler:^(AHKActionSheet *as) {
  3205. // close swipe
  3206. [self setEditing:NO animated:YES];
  3207. [self openWindowShare:_metadata];
  3208. }];
  3209. }
  3210. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3211. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brand]
  3212. backgroundColor:[UIColor whiteColor]
  3213. height: 50.0
  3214. type:AHKActionSheetButtonTypeDefault
  3215. handler:^(AHKActionSheet *as) {
  3216. // close swipe
  3217. [self setEditing:NO animated:YES];
  3218. [self performSelector:@selector(openIn:) withObject:_metadata];
  3219. }];
  3220. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3221. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brand]
  3222. backgroundColor:[UIColor whiteColor]
  3223. height: 50.0
  3224. type:AHKActionSheetButtonTypeDefault
  3225. handler:^(AHKActionSheet *as) {
  3226. // close swipe
  3227. [self setEditing:NO animated:YES];
  3228. //chiediamo il nome del file
  3229. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3230. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3231. alertView.tag = alertRename;
  3232. UITextField *textField = [alertView textFieldAtIndex:0];
  3233. textField.text = _metadata.fileNamePrint;
  3234. [alertView show];
  3235. }];
  3236. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3237. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brand]
  3238. backgroundColor:[UIColor whiteColor]
  3239. height: 50.0
  3240. type:AHKActionSheetButtonTypeDefault
  3241. handler:^(AHKActionSheet *as) {
  3242. // close swipe
  3243. [self setEditing:NO animated:YES];
  3244. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3245. }];
  3246. if (recordLocalFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3247. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3248. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brand]
  3249. backgroundColor:[UIColor whiteColor]
  3250. height: 50.0
  3251. type:AHKActionSheetButtonTypeDefault
  3252. handler:^(AHKActionSheet *as) {
  3253. // close swipe
  3254. [self setEditing:NO animated:YES];
  3255. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3256. }];
  3257. }
  3258. if (app.isCryptoCloudMode) {
  3259. [actionSheet addButtonWithTitle:titoloCriptaDecripta
  3260. image:[UIImage imageNamed:@"actionSheetCrypto"]
  3261. backgroundColor:[UIColor whiteColor]
  3262. height: 50.0
  3263. type:AHKActionSheetButtonTypeEncrypted
  3264. handler:^(AHKActionSheet *as) {
  3265. // close swipe
  3266. [self setEditing:NO animated:YES];
  3267. [self performSelector:@selector(cmdEncryptedDecryptedFile) withObject:nil];
  3268. }];
  3269. }
  3270. [actionSheet show];
  3271. }
  3272. /******************************************* TEMPLATE *******************************************/
  3273. if ([_metadata.type isEqualToString: k_metadataType_template]) {
  3274. [actionSheet addButtonWithTitle: _metadata.fileNamePrint
  3275. image: [UIImage imageNamed:_metadata.iconName]
  3276. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3277. height: 50.0
  3278. type: AHKActionSheetButtonTypeDisabled
  3279. handler: nil
  3280. ];
  3281. if ([_metadata.model isEqualToString:@"note"]) {
  3282. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3283. image:[UIImage imageNamed:@"actionSheetRename"]
  3284. backgroundColor:[UIColor whiteColor]
  3285. height: 50.0
  3286. type:AHKActionSheetButtonTypeDefault
  3287. handler:^(AHKActionSheet *as) {
  3288. // close swipe
  3289. [self setEditing:NO animated:YES];
  3290. //chiediamo il nome del file
  3291. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_rename_",nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(@"_cancel_",nil) otherButtonTitles:NSLocalizedString(@"_save_", nil), nil];
  3292. [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
  3293. alertView.tag = alertRename;
  3294. UITextField *textField = [alertView textFieldAtIndex:0];
  3295. textField.text = _metadata.fileNamePrint;
  3296. [alertView show];
  3297. }];
  3298. }
  3299. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3300. image:[UIImage imageNamed:@"actionSheetMove"]
  3301. backgroundColor:[UIColor whiteColor]
  3302. height: 50.0
  3303. type:AHKActionSheetButtonTypeDefault
  3304. handler:^(AHKActionSheet *as) {
  3305. // close swipe
  3306. [self setEditing:NO animated:YES];
  3307. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3308. }];
  3309. [actionSheet show];
  3310. }
  3311. }
  3312. - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
  3313. {
  3314. return NSLocalizedString(@"_delete_", nil);
  3315. }
  3316. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3317. {
  3318. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3319. if (metadata == nil || metadata.errorPasscode || (metadata.cryptated && [metadata.title length] == 0) || metadata.sessionTaskIdentifier >= 0 || metadata.sessionTaskIdentifier >= 0) return NO;
  3320. else return YES;
  3321. }
  3322. - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
  3323. {
  3324. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3325. if (_metadata.errorPasscode || (_metadata.cryptated && [_metadata.title length] == 0) || _metadata.sessionTaskIdentifier >= 0 || _metadata.sessionTaskIdentifier >= 0) return UITableViewCellEditingStyleNone;
  3326. else return UITableViewCellEditingStyleDelete;
  3327. }
  3328. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  3329. {
  3330. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3331. BOOL lockDirectory = NO;
  3332. // Directory locked ?
  3333. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account] addFileName:_metadata.fileNameData];
  3334. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil) lockDirectory = YES;
  3335. if (lockDirectory && editingStyle == UITableViewCellEditingStyleDelete) {
  3336. [app messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  3337. return;
  3338. }
  3339. if (editingStyle == UITableViewCellEditingStyleDelete) {
  3340. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  3341. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil)
  3342. style:UIAlertActionStyleDestructive
  3343. handler:^(UIAlertAction *action) {
  3344. [self performSelector:@selector(deleteFile) withObject:nil];
  3345. }]];
  3346. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil)
  3347. style:UIAlertActionStyleCancel
  3348. handler:^(UIAlertAction *action) {
  3349. [alertController dismissViewControllerAnimated:YES completion:nil];
  3350. }]];
  3351. alertController.popoverPresentationController.sourceView = self.view;
  3352. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  3353. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3354. [alertController.view layoutIfNeeded];
  3355. [self presentViewController:alertController animated:YES completion:nil];
  3356. }
  3357. }
  3358. #pragma --------------------------------------------------------------------------------------------
  3359. #pragma mark - ==== Datasource ====
  3360. #pragma --------------------------------------------------------------------------------------------
  3361. - (void)clearDateReadDataSource:(NSNotification *)notification
  3362. {
  3363. _dateReadDataSource = Nil;
  3364. [self reloadDatasource];
  3365. }
  3366. - (void)reloadDatasource
  3367. {
  3368. [self reloadDatasource:_serverUrl fileID:nil selector:nil];
  3369. }
  3370. - (void)reloadDatasource:(NSString *)serverUrl fileID:(NSString *)fileID selector:(NSString *)selector
  3371. {
  3372. // test
  3373. if (app.activeAccount.length == 0 || serverUrl.length == 0)
  3374. return;
  3375. // Search Mode
  3376. if(_isSearchMode) {
  3377. if ([selector length] == 0 || [selector isEqualToString:selectorSearch]) {
  3378. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3379. } else {
  3380. [self readFolderWithForced:NO serverUrl:serverUrl];
  3381. }
  3382. [self tableViewReload];
  3383. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3384. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3385. _noFilesSearchDescription = @"";
  3386. }
  3387. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3388. _noFilesSearchTitle = @"";
  3389. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3390. }
  3391. [self.tableView reloadEmptyDataSet];
  3392. return;
  3393. }
  3394. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3395. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3396. if ([selector isEqualToString:selectorDownloadSynchronize]) {
  3397. [app.activeTransfers reloadDatasource];
  3398. } else {
  3399. CCMain *main = [app.listMainVC objectForKey:serverUrl];
  3400. if (main) {
  3401. [main reloadDatasource];
  3402. } else {
  3403. [self tableViewReload];
  3404. [app.activeTransfers reloadDatasource];
  3405. }
  3406. }
  3407. return;
  3408. }
  3409. // Offline folder ?
  3410. _isOfflineServerUrl = [CCCoreData isOfflineDirectoryServerUrl:_serverUrl activeAccount:app.activeAccount];
  3411. [app.activeTransfers reloadDatasource];
  3412. // Settaggio variabili per le ottimizzazioni
  3413. _directoryGroupBy = [CCUtility getGroupBySettings];
  3414. _directoryOrder = [CCUtility getOrderSettings];
  3415. // Controllo data lettura Data Source
  3416. NSDate *dateDateRecordDirectory = [CCCoreData getDateReadDirectoryID:[CCCoreData getDirectoryIDFromServerUrl:_serverUrl activeAccount:app.activeAccount] activeAccount:app.activeAccount];
  3417. dateDateRecordDirectory = nil;
  3418. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3419. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3420. _dateReadDataSource = [NSDate date];
  3421. // Data Source
  3422. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPreficate:[NSPredicate predicateWithFormat:@"(account == %@) AND (directoryID == %@)", app.activeAccount, [CCCoreData getDirectoryIDFromServerUrl:serverUrl activeAccount:app.activeAccount]] sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  3423. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3424. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy replaceDateToExifDate:NO activeAccount:app.activeAccount];
  3425. } else {
  3426. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3427. }
  3428. [self tableViewReload];
  3429. }
  3430. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3431. {
  3432. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3433. if (selectedRows.count > 0) {
  3434. for (NSIndexPath *selectionIndex in selectedRows) {
  3435. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3436. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3437. [metadatas addObject:metadata];
  3438. }
  3439. }
  3440. return metadatas;
  3441. }
  3442. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3443. {
  3444. NSInteger section = indexPath.section + 1;
  3445. NSInteger row = indexPath.row + 1;
  3446. NSInteger totSections =[_sectionDataSource.sections count] ;
  3447. if ((totSections < section) || (section > totSections)) {
  3448. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3449. return nil;
  3450. }
  3451. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3452. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3453. if (fileIDs) {
  3454. NSInteger totRows =[fileIDs count] ;
  3455. if ((totRows < row) || (row > totRows)) {
  3456. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3457. return nil;
  3458. }
  3459. } else {
  3460. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3461. return nil;
  3462. }
  3463. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3464. return [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3465. }
  3466. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3467. {
  3468. NSInteger totSections =[_sectionDataSource.sections count] ;
  3469. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3470. #if DEBUG
  3471. 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];
  3472. [alertView show];
  3473. #endif
  3474. return nil;
  3475. }
  3476. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3477. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3478. }
  3479. #pragma --------------------------------------------------------------------------------------------
  3480. #pragma mark - ==== Table ====
  3481. #pragma --------------------------------------------------------------------------------------------
  3482. - (void)tableViewSelect:(BOOL)edit
  3483. {
  3484. // chiudiamo eventuali swipe aperti
  3485. if (edit) [self.tableView setEditing:NO animated:NO];
  3486. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3487. [self.tableView setEditing:edit animated:YES];
  3488. _isSelectedMode = edit;
  3489. if (edit)
  3490. [self setUINavigationBarSelected];
  3491. else
  3492. [self setUINavigationBarDefault];
  3493. [self setTitle];
  3494. }
  3495. - (void)tableViewReload
  3496. {
  3497. // ricordiamoci le row selezionate
  3498. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3499. [self.tableView reloadData];
  3500. for (NSIndexPath *path in indexPaths)
  3501. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3502. [self setTableViewFooter];
  3503. if (self.tableView.editing)
  3504. [self setTitle];
  3505. }
  3506. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3507. {
  3508. return 60;
  3509. }
  3510. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3511. {
  3512. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3513. }
  3514. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3515. {
  3516. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3517. }
  3518. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3519. {
  3520. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3521. NSString *sectionTitle = [sections objectAtIndex:section];
  3522. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3523. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3524. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3525. return 20.f;
  3526. }
  3527. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3528. {
  3529. float shift;
  3530. UIVisualEffectView *visualEffectView;
  3531. // Titolo
  3532. NSString *titleSection;
  3533. // Controllo
  3534. if ([_sectionDataSource.sections count] == 0)
  3535. return nil;
  3536. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]]) titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3537. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]]) titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3538. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3539. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3540. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3541. else titleSection = NSLocalizedString(titleSection,nil);
  3542. // Formato titolo
  3543. NSString *currentDevice = [CCUtility currentDevice];
  3544. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3545. visualEffectView = [[UIVisualEffectView alloc] init];
  3546. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3547. } else {
  3548. UIVisualEffect *blurEffect;
  3549. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3550. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3551. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3552. }
  3553. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3554. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) shift = - 35;
  3555. else shift = - 20;
  3556. } else shift = - 10;
  3557. // Title
  3558. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3559. titleLabel.backgroundColor = [UIColor clearColor];
  3560. titleLabel.textColor = [UIColor blackColor];
  3561. titleLabel.font = [UIFont systemFontOfSize:12];
  3562. titleLabel.textAlignment = NSTextAlignmentLeft;
  3563. titleLabel.text = titleSection;
  3564. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3565. [visualEffectView addSubview:titleLabel];
  3566. // Elements
  3567. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3568. elementLabel.backgroundColor = [UIColor clearColor];
  3569. elementLabel.textColor = [UIColor blackColor];;
  3570. elementLabel.font = [UIFont systemFontOfSize:12];
  3571. elementLabel.textAlignment = NSTextAlignmentRight;
  3572. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3573. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3574. NSUInteger rowsCount = [metadatas count];
  3575. if (rowsCount == 0) return nil;
  3576. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3577. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3578. [visualEffectView addSubview:elementLabel];
  3579. return visualEffectView;
  3580. }
  3581. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3582. {
  3583. return [_sectionDataSource.sections indexOfObject:title];
  3584. }
  3585. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3586. {
  3587. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3588. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3589. else
  3590. return nil;
  3591. }
  3592. /*
  3593. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3594. {
  3595. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3596. }
  3597. }
  3598. */
  3599. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3600. {
  3601. NSString *typeCell;
  3602. NSString *dataFile;
  3603. NSString *lunghezzaFile;
  3604. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3605. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:metadata.directoryID activeAccount:metadata.account];
  3606. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3607. else typeCell = @"CellMainTransfer";
  3608. if (!metadata)
  3609. return [tableView dequeueReusableCellWithIdentifier:typeCell];
  3610. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3611. // separator
  3612. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3613. // change color selection
  3614. UIView *selectionColor = [[UIView alloc] init];
  3615. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3616. cell.selectedBackgroundView = selectionColor;
  3617. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [UIColor whiteColor];
  3618. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3619. // ----------------------------------------------------------------------------------------------------------
  3620. // DEFAULT
  3621. // ----------------------------------------------------------------------------------------------------------
  3622. cell.fileImageView.image = nil;
  3623. cell.statusImageView.image = nil;
  3624. cell.offlineImageView.image = nil;
  3625. cell.synchronizedImageView.image = nil;
  3626. cell.sharedImageView.image = nil;
  3627. cell.labelTitle.enabled = YES;
  3628. cell.labelTitle.text = @"";
  3629. cell.labelInfoFile.enabled = YES;
  3630. cell.labelInfoFile.text = @"";
  3631. cell.progressView.progress = 0.0;
  3632. cell.progressView.hidden = YES;
  3633. cell.cancelTaskButton.hidden = YES;
  3634. cell.reloadTaskButton.hidden = YES;
  3635. cell.stopTaskButton.hidden = YES;
  3636. // Encrypted color
  3637. if (metadata.cryptated) {
  3638. cell.labelTitle.textColor = [NCBrandColor sharedInstance].cryptocloud;
  3639. } else {
  3640. cell.labelTitle.textColor = [UIColor blackColor];
  3641. }
  3642. // ----------------------------------------------------------------------------------------------------------
  3643. // File Name & Folder
  3644. // ----------------------------------------------------------------------------------------------------------
  3645. // nome del file
  3646. cell.labelTitle.text = metadata.fileNamePrint;
  3647. // è una directory
  3648. if (metadata.directory) {
  3649. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3650. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3651. lunghezzaFile = @" ";
  3652. // ----------------------------------------------------------------------------------------------------------
  3653. // Favorite Folder
  3654. // ----------------------------------------------------------------------------------------------------------
  3655. if (metadata.favorite) {
  3656. cell.offlineImageView.image = [UIImage imageNamed:@"favorite"];
  3657. }
  3658. } else {
  3659. // File
  3660. dataFile = [CCUtility dateDiff:metadata.date];
  3661. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3662. // Plist ancora da scaricare
  3663. if (metadata.cryptated && [metadata.title length] == 0) {
  3664. dataFile = @" ";
  3665. lunghezzaFile = @" ";
  3666. }
  3667. TableLocalFile *recordLocalFile = [CCCoreData getLocalFileWithFileID:metadata.fileID activeAccount:app.activeAccount];
  3668. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3669. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3670. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3671. if ([metadata.type isEqualToString: k_metadataType_template] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO)
  3672. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", dataFile];
  3673. if ([metadata.type isEqualToString: k_metadataType_file] && [dataFile isEqualToString:@" "] == NO && [lunghezzaFile isEqualToString:@" "] == NO) {
  3674. if (recordLocalFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, metadata.fileID]])
  3675. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ • %@", dataFile, lunghezzaFile];
  3676. else
  3677. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ ◦ %@", dataFile, lunghezzaFile];
  3678. }
  3679. // Plist ancora da scaricare
  3680. if ([dataFile isEqualToString:@" "] && [lunghezzaFile isEqualToString:@" "])
  3681. cell.labelInfoFile.text = NSLocalizedString(@"_no_plist_pull_down_",nil);
  3682. cell.accessoryType = UITableViewCellAccessoryNone;
  3683. }
  3684. // ----------------------------------------------------------------------------------------------------------
  3685. // File Image View
  3686. // ----------------------------------------------------------------------------------------------------------
  3687. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3688. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]]) {
  3689. cell.fileImageView.image = [app.icoImagesCache objectForKey:metadata.fileID];
  3690. if (cell.fileImageView.image == nil) {
  3691. NSString *fileID = metadata.fileID;
  3692. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3693. UIImage *image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, fileID]];
  3694. [app.icoImagesCache setObject:image forKey:fileID];
  3695. dispatch_async(dispatch_get_main_queue(), ^{
  3696. CCCellMainTransfer *cell = [tableView cellForRowAtIndexPath:indexPath];
  3697. if (cell)
  3698. cell.fileImageView.image = image;
  3699. });
  3700. });
  3701. }
  3702. } else {
  3703. if (metadata.directory)
  3704. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:metadata.iconName] color:[NCBrandColor sharedInstance].brand];
  3705. else
  3706. cell.fileImageView.image = [UIImage imageNamed:metadata.iconName];
  3707. if (metadata.thumbnailExists)
  3708. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3709. }
  3710. // ----------------------------------------------------------------------------------------------------------
  3711. // Image Status cyptated & Lock Passcode
  3712. // ----------------------------------------------------------------------------------------------------------
  3713. // File Cyptated
  3714. if (metadata.cryptated && metadata.directory == NO && [metadata.type isEqualToString: k_metadataType_template] == NO) {
  3715. cell.statusImageView.image = [UIImage imageNamed:@"lock"];
  3716. }
  3717. // Directory con passcode lock attivato
  3718. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileNameData];
  3719. if (metadata.directory && ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length]))
  3720. cell.statusImageView.image = [UIImage imageNamed:@"passcode"];
  3721. // ----------------------------------------------------------------------------------------------------------
  3722. // Offline
  3723. // ----------------------------------------------------------------------------------------------------------
  3724. BOOL isOfflineFile = [CCCoreData isOfflineLocalFileID:metadata.fileID activeAccount:app.activeAccount];
  3725. if (isOfflineFile) {
  3726. cell.offlineImageView.image = [UIImage imageNamed:@"offline"];
  3727. }
  3728. // ----------------------------------------------------------------------------------------------------------
  3729. // Favorite
  3730. // ----------------------------------------------------------------------------------------------------------
  3731. if (metadata.favorite) {
  3732. cell.offlineImageView.image = [UIImage imageNamed:@"favorite"];
  3733. }
  3734. // ----------------------------------------------------------------------------------------------------------
  3735. // Share
  3736. // ----------------------------------------------------------------------------------------------------------
  3737. NSString *shareLink = [app.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3738. NSString *shareUserAndGroup = [app.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3739. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3740. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3741. // Aggiungiamo il Tap per le shared
  3742. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3743. if (isShare) {
  3744. if (metadata.directory) {
  3745. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3746. cell.sharedImageView.userInteractionEnabled = NO;
  3747. } else {
  3748. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3749. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3750. [tap setNumberOfTapsRequired:1];
  3751. cell.sharedImageView.userInteractionEnabled = YES;
  3752. [cell.sharedImageView addGestureRecognizer:tap];
  3753. }
  3754. }
  3755. if (isMounted) {
  3756. if (metadata.directory) {
  3757. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brand];
  3758. cell.sharedImageView.userInteractionEnabled = NO;
  3759. } else {
  3760. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brand];
  3761. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3762. [tap setNumberOfTapsRequired:1];
  3763. cell.sharedImageView.userInteractionEnabled = YES;
  3764. [cell.sharedImageView addGestureRecognizer:tap];
  3765. }
  3766. }
  3767. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3768. if (metadata.directory) {
  3769. if ([shareLink length] > 0)
  3770. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brand];
  3771. if ([shareUserAndGroup length] > 0)
  3772. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brand];
  3773. cell.sharedImageView.userInteractionEnabled = NO;
  3774. } else {
  3775. if ([shareLink length] > 0)
  3776. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brand];
  3777. if ([shareUserAndGroup length] > 0)
  3778. cell.sharedImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brand];
  3779. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3780. [tap setNumberOfTapsRequired:1];
  3781. cell.sharedImageView.userInteractionEnabled = YES;
  3782. [cell.sharedImageView addGestureRecognizer:tap];
  3783. }
  3784. }
  3785. } else {
  3786. cell.sharedImageView.userInteractionEnabled = NO;
  3787. }
  3788. // ----------------------------------------------------------------------------------------------------------
  3789. // downloadFile
  3790. // ----------------------------------------------------------------------------------------------------------
  3791. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3792. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusdownloadcrypto"];
  3793. else cell.statusImageView.image = [UIImage imageNamed:@"statusdownload"];
  3794. // sessionTaskIdentifier : RELOAD + STOP
  3795. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3796. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3797. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3798. cell.cancelTaskButton.hidden = NO;
  3799. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3800. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3801. cell.reloadTaskButton.hidden = NO;
  3802. }
  3803. // sessionTaskIdentifierPlist : RELOAD
  3804. if (metadata.sessionTaskIdentifierPlist != k_taskIdentifierDone) {
  3805. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3806. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3807. cell.reloadTaskButton.hidden = NO;
  3808. }
  3809. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3810. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3811. if (progress > 0) {
  3812. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3813. else cell.progressView.progressTintColor = [UIColor blackColor];
  3814. cell.progressView.progress = progress;
  3815. cell.progressView.hidden = NO;
  3816. }
  3817. // ----------------------------------------------------------------------------------------------------------
  3818. // downloadFile Error
  3819. // ----------------------------------------------------------------------------------------------------------
  3820. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3821. cell.statusImageView.image = [UIImage imageNamed:@"statuserror"];
  3822. if ([metadata.sessionError length] == 0)
  3823. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3824. else
  3825. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3826. }
  3827. }
  3828. // ----------------------------------------------------------------------------------------------------------
  3829. // uploadFile
  3830. // ----------------------------------------------------------------------------------------------------------
  3831. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3832. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusuploadcrypto"];
  3833. else cell.statusImageView.image = [UIImage imageNamed:@"statusupload"];
  3834. if (metadata.cryptated)[cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetaskcrypto"] forState:UIControlStateNormal];
  3835. else [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3836. cell.cancelTaskButton.hidden = NO;
  3837. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3838. if (metadata.cryptated)[cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtaskcrypto"] forState:UIControlStateNormal];
  3839. else [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3840. if (metadata.cryptated) cell.statusImageView.image = [UIImage imageNamed:@"statusstopcrypto"];
  3841. else cell.statusImageView.image = [UIImage imageNamed:@"statusstop"];
  3842. cell.reloadTaskButton.hidden = NO;
  3843. cell.stopTaskButton.hidden = YES;
  3844. } else {
  3845. if (metadata.cryptated)[cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptaskcrypto"] forState:UIControlStateNormal];
  3846. else [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3847. cell.stopTaskButton.hidden = NO;
  3848. cell.reloadTaskButton.hidden = YES;
  3849. }
  3850. // se non c'è una preview in bianconero metti l'immagine di default
  3851. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", app.directoryUser, metadata.fileID]] == NO)
  3852. cell.fileImageView.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brand];
  3853. cell.labelTitle.enabled = NO;
  3854. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3855. float progress = [[app.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3856. if (progress > 0) {
  3857. if (metadata.cryptated) cell.progressView.progressTintColor = [NCBrandColor sharedInstance].cryptocloud;
  3858. else cell.progressView.progressTintColor = [UIColor blackColor];
  3859. cell.progressView.progress = progress;
  3860. cell.progressView.hidden = NO;
  3861. }
  3862. // ----------------------------------------------------------------------------------------------------------
  3863. // uploadFileError
  3864. // ----------------------------------------------------------------------------------------------------------
  3865. if (metadata.sessionTaskIdentifier == k_taskIdentifierError || metadata.sessionTaskIdentifierPlist == k_taskIdentifierError) {
  3866. cell.labelTitle.enabled = NO;
  3867. cell.statusImageView.image = [UIImage imageNamed:@"statuserror"];
  3868. if ([metadata.sessionError length] == 0)
  3869. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3870. else
  3871. cell.labelInfoFile.text = [CCError manageErrorKCF:[metadata.sessionError integerValue] withNumberError:NO];
  3872. }
  3873. }
  3874. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3875. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3876. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3877. return cell;
  3878. }
  3879. - (void)setTableViewFooter
  3880. {
  3881. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3882. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3883. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3884. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3885. UIFont *appFont = [UIFont systemFontOfSize:12];
  3886. footerLabel.font = appFont;
  3887. footerLabel.textColor = [UIColor grayColor];
  3888. footerLabel.backgroundColor = [UIColor clearColor];
  3889. footerLabel.textAlignment = NSTextAlignmentCenter;
  3890. NSString *folders;
  3891. NSString *files;
  3892. NSString *footerText;
  3893. if (_sectionDataSource.directories > 1) {
  3894. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3895. } else if (_sectionDataSource.directories == 1){
  3896. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3897. } else {
  3898. folders = @"";
  3899. }
  3900. if (_sectionDataSource.files > 1) {
  3901. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3902. } else if (_sectionDataSource.files == 1){
  3903. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3904. } else {
  3905. files = @"";
  3906. }
  3907. if ([folders isEqualToString:@""]) {
  3908. footerText = files;
  3909. } else if ([files isEqualToString:@""]) {
  3910. footerText = folders;
  3911. } else {
  3912. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3913. }
  3914. footerLabel.text = footerText;
  3915. [footerView addSubview:footerLabel];
  3916. [self.tableView setTableFooterView:footerView];
  3917. }
  3918. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3919. {
  3920. NSString *textMessage;
  3921. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3922. // settiamo il record file.
  3923. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3924. // se non può essere selezionata deseleziona
  3925. if ([cell isEditing] == NO)
  3926. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3927. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3928. if (self.tableView.editing) {
  3929. [self setTitle];
  3930. return;
  3931. }
  3932. // test crash
  3933. NSArray *metadatas = [_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:indexPath.section]];
  3934. if (indexPath.row >= [metadatas count]) return;
  3935. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  3936. // se è in corso una sessione
  3937. if ([_metadata.session length] > 0) return;
  3938. if (_metadata.errorPasscode) {
  3939. // se UUID è nil lo sta ancora caricando quindi esci
  3940. if (!_metadata.uuid) return;
  3941. // esiste un hint ??
  3942. NSString *hint = [[CCCrypto sharedManager] getHintFromFile:_metadata.fileName isLocal:NO directoryUser:app.directoryUser];
  3943. // qui !! la richiesta della nuova passcode
  3944. if ([_metadata.uuid isEqualToString:[CCUtility getUUID]]) {
  3945. // stesso UUID ... la password è stata modificata !!!!!!
  3946. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_same_device_different_passcode_hint_",nil), hint];
  3947. else textMessage = NSLocalizedString(@"_same_device_different_passcode_", nil);
  3948. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3949. [alertView show];
  3950. } else {
  3951. // UUID diverso.
  3952. if (hint) textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_hint_",nil), _metadata.nameCurrentDevice, hint];
  3953. else textMessage = [NSString stringWithFormat:NSLocalizedString(@"_file_encrypted_another_device_",nil), _metadata.nameCurrentDevice];
  3954. UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"_error_", nil) message:textMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"_ok_", nil), nil];
  3955. [alertView show];
  3956. }
  3957. // chiediamo la passcode e ricarichiamo tutto.
  3958. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3959. viewController.delegate = self;
  3960. viewController.fromType = CCBKPasscodeFromPasscode;
  3961. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3962. viewController.passcodeInputView.maximumLength = 64;
  3963. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3964. viewController.inputViewTitlePassword = NO;
  3965. viewController.title = [NCBrandOptions sharedInstance].brand;
  3966. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3967. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  3968. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3969. [self presentViewController:navigationController animated:YES completion:nil];
  3970. }
  3971. // modello o plist con il title a 0 allora è andato storto qualcosa ... ricaricalo
  3972. if (_metadata.cryptated && [_metadata.title length] == 0) {
  3973. NSString* selector;
  3974. if ([_metadata.type isEqualToString: k_metadataType_template]) selector = selectorLoadModelView;
  3975. else selector = selectorLoadPlist;
  3976. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:NO downloadPlist:YES selector:selector selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3977. return;
  3978. }
  3979. // se il plist è caricato ed è un modello aprilo
  3980. if ([_metadata.type isEqualToString:k_metadataType_template]) [self openModel:_metadata.model isNew:false];
  3981. // file
  3982. if (_metadata.directory == NO && _metadata.errorPasscode == NO && [_metadata.type isEqualToString: k_metadataType_file]) {
  3983. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3984. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", app.directoryUser, _metadata.fileID]]) {
  3985. [self downloadFileSuccess:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil];
  3986. } else {
  3987. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileID serverUrl:serverUrl downloadData:YES downloadPlist:NO selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3988. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3989. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3990. }
  3991. }
  3992. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3993. }
  3994. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3995. {
  3996. [self setTitle];
  3997. }
  3998. #pragma --------------------------------------------------------------------------------------------
  3999. #pragma mark ===== Synchronize Folder Cell =====
  4000. #pragma --------------------------------------------------------------------------------------------
  4001. - (void)synchronizeFolderGraphicsServerUrl:(NSString *)serverUrl animation:(BOOL)animation
  4002. {
  4003. BOOL cryptated = NO;
  4004. CCCellMain *cell;
  4005. for (NSString* fileID in _sectionDataSource.allRecordsDataSource) {
  4006. tableMetadata *recordMetadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4007. if (recordMetadata.directory == NO)
  4008. continue;
  4009. if ([[CCUtility stringAppendServerUrl:_serverUrl addFileName:recordMetadata.fileNameData] isEqualToString:serverUrl]) {
  4010. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:recordMetadata.fileID];
  4011. cell = (CCCellMain *)[self.tableView cellForRowAtIndexPath:indexPath];
  4012. cryptated = recordMetadata.cryptated;
  4013. break;
  4014. }
  4015. }
  4016. if (!cell)
  4017. return;
  4018. if (animation) {
  4019. NSURL *myURL;
  4020. if (cryptated)
  4021. myURL = [[NSBundle mainBundle] URLForResource: @"synchronizedcrypto" withExtension:@"gif"];
  4022. else
  4023. myURL = [[NSBundle mainBundle] URLForResource: @"synchronized" withExtension:@"gif"];
  4024. } else {
  4025. cell.synchronizedImageView.image = nil;
  4026. }
  4027. }
  4028. #pragma --------------------------------------------------------------------------------------------
  4029. #pragma mark ===== Navigation ====
  4030. #pragma --------------------------------------------------------------------------------------------
  4031. - (BOOL)shouldPerformSegue
  4032. {
  4033. // if background return
  4034. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  4035. if (self.view.window == NO)
  4036. return NO;
  4037. // Collapsed ma siamo già in detail esci
  4038. if (self.splitViewController.isCollapsed)
  4039. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  4040. // Video in esecuzione esci
  4041. if (_detailViewController.photoBrowser.currentVideoPlayerViewController.isViewLoaded && _detailViewController.photoBrowser.currentVideoPlayerViewController.view.window) return NO;
  4042. return YES;
  4043. }
  4044. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  4045. {
  4046. id viewController = segue.destinationViewController;
  4047. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  4048. tableMetadata *metadata;
  4049. if ([viewController isKindOfClass:[UINavigationController class]]) {
  4050. UINavigationController *nav = viewController;
  4051. _detailViewController = (CCDetail *)nav.topViewController;
  4052. } else {
  4053. _detailViewController = segue.destinationViewController;
  4054. }
  4055. if ([sender isKindOfClass:[tableMetadata class]]) {
  4056. metadata = sender;
  4057. [allRecordsDataSourceImagesVideos addObject:sender];
  4058. } else {
  4059. metadata = _metadata;
  4060. for (NSString *fileID in _sectionDataSource.allFileID) {
  4061. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  4062. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])
  4063. [allRecordsDataSourceImagesVideos addObject:metadata];
  4064. }
  4065. }
  4066. _detailViewController.metadataDetail = metadata;
  4067. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  4068. _detailViewController.dateFilterQuery = nil;
  4069. _detailViewController.isCameraUpload = NO;
  4070. [_detailViewController setTitle:metadata.fileNamePrint];
  4071. }
  4072. // can i go to next viewcontroller
  4073. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  4074. {
  4075. NSString *nomeDir;
  4076. if(self.tableView.editing == NO && _metadata.errorPasscode == NO){
  4077. NSString *serverUrl = [CCCoreData getServerUrlFromDirectoryID:_metadata.directoryID activeAccount:_metadata.account];
  4078. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileNameData];
  4079. // 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
  4080. if ([CCCoreData isDirectoryLock:lockServerUrl activeAccount:app.activeAccount] && [[CCUtility getBlockCode] length] && app.sessionePasscodeLock == nil && controlPasscode) {
  4081. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  4082. viewController.delegate = self;
  4083. viewController.fromType = CCBKPasscodeFromLockDirectory;
  4084. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  4085. viewController.inputViewTitlePassword = YES;
  4086. if ([CCUtility getSimplyBlockCode]) {
  4087. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  4088. viewController.passcodeInputView.maximumLength = 6;
  4089. } else {
  4090. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  4091. viewController.passcodeInputView.maximumLength = 64;
  4092. }
  4093. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  4094. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  4095. viewController.touchIDManager = touchIDManager;
  4096. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  4097. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  4098. viewController.navigationItem.leftBarButtonItem.tintColor = [NCBrandColor sharedInstance].cryptocloud;
  4099. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  4100. [self presentViewController:navController animated:YES completion:nil];
  4101. return;
  4102. }
  4103. if (_metadata.cryptated) nomeDir = [_metadata.fileName substringToIndex:[_metadata.fileName length]-6];
  4104. else nomeDir = _metadata.fileName;
  4105. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  4106. CCMain *viewController = [app.listMainVC objectForKey:serverUrlPush];
  4107. if (viewController.isViewLoaded == false || viewController == nil) {
  4108. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMainVC"];
  4109. viewController.isFolderEncrypted = _metadata.cryptated;
  4110. viewController.serverUrl = serverUrlPush;
  4111. viewController.titleMain = _metadata.fileNamePrint;
  4112. viewController.textBackButton = _titleMain;
  4113. // save self
  4114. [app.listMainVC setObject:viewController forKey:serverUrlPush];
  4115. }
  4116. // OFF SearchBar
  4117. [viewController cancelSearchBar];
  4118. [self.navigationController pushViewController:viewController animated:YES];
  4119. }
  4120. }
  4121. @end