CCMain.m 257 KB

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