CCMain.m 260 KB

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