CCMain.m 259 KB

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